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
9cff829ca3b5d14e6a12778be374842f6228e41f
src/base/beans/util-beans-objects-enums.adb
src/base/beans/util-beans-objects-enums.adb
----------------------------------------------------------------------- -- 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;
----------------------------------------------------------------------- -- util-beans-objects-enums -- Helper conversion for discrete types -- Copyright (C) 2010, 2016, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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_RECORD => raise Constraint_Error with "Cannot convert a record 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;
Handle the TYPE_RECORD
Handle the TYPE_RECORD
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e54d5d1a99a6323442859a9d067d2690f665b39c
src/asf-components-core-views.adb
src/asf-components-core-views.adb
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use ASF; use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. -- ------------------------------ overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String is Name : constant String := UI.Get_Attribute ("name", Context); begin if Name'Length > 0 then return Context.Get_Parameter (Name); else return Html.Forms.UIInput (UI).Get_Parameter (Context); end if; end Get_Parameter; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. -- ------------------------------ overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String is Name : constant String := UI.Get_Attribute ("name", Context); begin if Name'Length > 0 then return Context.Get_Parameter (Name); else return Html.Forms.UIInput (UI).Get_Parameter (Context); end if; end Get_Parameter; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
Remove unused use clauses
Remove unused use clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
67238c7770ec4d5573715c32cfca2c73159d1940
src/wiki-plugins-templates.adb
src/wiki-plugins-templates.adb
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- 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.Parsers; package body Wiki.Plugins.Templates is -- ------------------------------ -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is P : Wiki.Parsers.Parser; Content : Wiki.Strings.UString; begin Template_Plugin'Class (Plugin).Get_Template (Params, Content); P.Set_Context (Context); P.Parse (Content, Document); end Expand; end Wiki.Plugins.Templates;
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Directories; with Wiki.Parsers; with Wiki.Streams.Text_IO; package body Wiki.Plugins.Templates is use Ada.Strings.Unbounded; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is P : Wiki.Parsers.Parser; Content : Wiki.Strings.UString; begin Template_Plugin'Class (Plugin).Get_Template (Params, Content); P.Set_Context (Context); P.Parse (Content, Document); end Expand; -- ------------------------------ -- Find a plugin knowing its name. -- ------------------------------ overriding function Find (Factory : in File_Template_Plugin; Name : in String) return Wiki_Plugin_Access is Path : constant String := Ada.Directories.Compose (To_String (Factory.Path), Name); begin if Ada.Directories.Exists (Path) then return Factory'Unrestricted_Access; else return null; end if; end Find; -- ------------------------------ -- Set the directory path that contains template files. -- ------------------------------ procedure Set_Template_Path (Plugin : in out File_Template_Plugin; Path : in String) is begin Plugin.Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end Set_Template_Path; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- Read the file whose basename correspond to the first parameter and parse that file -- in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out File_Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is First : constant Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Name : constant String := Wiki.Attributes.Get_Value (First); Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; P : Wiki.Parsers.Parser; Path : constant String := Ada.Directories.Compose (To_String (Plugin.Path), Name); begin Input.Open (Path, "WCEM=8"); P.Set_Context (Context); P.Parse (Input'Unchecked_Access, Document); Input.Close; exception when Ada.IO_Exceptions.Name_Error => null; end Expand; end Wiki.Plugins.Templates;
Implement the File_Template_Plugin operations
Implement the File_Template_Plugin operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
10b50efd03fa2f62b483d47e38c8f4842774d6cf
src/mysql/ado-drivers-connections-mysql.ads
src/mysql/ado-drivers-connections-mysql.ads
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 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 Mysql.Mysql; use Mysql.Mysql; package ADO.Drivers.Connections.Mysql is type Mysql_Driver is limited private; -- Initialize the Mysql driver. procedure Initialize; private -- Create a new MySQL connection using the configuration parameters. procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Mysql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Mysql driver. overriding procedure Finalize (D : in out Mysql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String := Null_Unbounded_String; Server_Name : Unbounded_String := Null_Unbounded_String; Login_Name : Unbounded_String := Null_Unbounded_String; Password : Unbounded_String := Null_Unbounded_String; Server : Mysql_Access := null; Connected : Boolean := False; -- MySQL autocommit flag Autocommit : Boolean := True; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 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 Mysql.Mysql; use Mysql.Mysql; package ADO.Drivers.Connections.Mysql is type Mysql_Driver is limited private; -- Initialize the Mysql driver. procedure Initialize; private -- Create a new MySQL connection using the configuration parameters. procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Mysql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Mysql driver. overriding procedure Finalize (D : in out Mysql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String := Null_Unbounded_String; Server_Name : Unbounded_String := Null_Unbounded_String; Login_Name : Unbounded_String := Null_Unbounded_String; Password : Unbounded_String := Null_Unbounded_String; Server : Mysql_Access := null; Connected : Boolean := False; -- MySQL autocommit flag Autocommit : Boolean := True; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Create the database and initialize it with the schema SQL file. overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Drivers.Connections.Mysql;
Declare the Create_Database procedure
Declare the Create_Database procedure
Ada
apache-2.0
stcarrez/ada-ado
745f8038509067434f932041822208a2fa40a47d
src/core/texts/util-texts-builders.ads
src/core/texts/util-texts-builders.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Input); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Element_Type); -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive); generic with procedure Process (Content : in out Input; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)); generic with procedure Process (Content : in Input); procedure Inline_Iterate (Source : in Builder); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Element_Type; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. generic with function Index (Content : in Input) return Natural; function Find (Source : in Builder; Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Input); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Element_Type); -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive); generic with procedure Process (Content : in out Input; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)); generic with procedure Process (Content : in Input); procedure Inline_Iterate (Source : in Builder); generic with procedure Process (Content : in out Input); procedure Inline_Update (Source : in out Builder); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Element_Type; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. generic with function Index (Content : in Input) return Natural; function Find (Source : in Builder; Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
Add Inline_Update generic procedure
Add Inline_Update generic procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
07aefbf9596950319140e334787a4191e7acf3b5
awa/src/awa-permissions-services.adb
awa/src/awa-permissions-services.adb
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- 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 ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Util.Serialize.IO.XML; with Security.Controllers.Roles; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use Util.Log; use ADO.Sessions; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Permissions.Permission_Manager_Access; M : constant Security.Permissions.Permission_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Read the policy file -- ------------------------------ overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Security.Permissions.Reader_Config (Reader, Manager'Unchecked_Access); package Role_Config is new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); -- package Entity_Config is -- new AWA.Permissions.Controllers.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); -- pragma Warnings (Off, Entity_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Permissions.Permission_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager; begin Result.Set_Application (App); return Result.all'Access; end Create_Permission_Manager; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- 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 ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Util.Serialize.IO.XML; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use Util.Log; use ADO.Sessions; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Policies.Policy_Manager_Access; M : constant Security.Policies.Policy_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Read the policy file -- ------------------------------ overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; -- package Policy_Config is -- new Security.Permissions.Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); -- pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); -- pragma Warnings (Off, Entity_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager (10); begin Result.Set_Application (App); return Result.all'Access; end Create_Permission_Manager; end AWA.Permissions.Services;
Fix compilation after refactoring Security package
Fix compilation after refactoring Security package
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d2ab93604456cea4074a901a52f844f86644af3b
awa/regtests/awa-events-services-tests.adb
awa/regtests/awa-events-services-tests.adb
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Util.Concurrent.Counters; with EL.Beans; with EL.Expressions; with EL.Contexts.Default; with ASF.Applications; with ASF.Servlets.Faces; with AWA.Applications; with AWA.Applications.Configs; with AWA.Applications.Factory; with AWA.Events.Action_Method; with AWA.Services.Contexts; with AWA.Events.Queues; with AWA.Events.Services; package body AWA.Events.Services.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests"); package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name", Test_Get_Event_Name'Access); Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous", Test_Dispatch_Synchronous'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo", Test_Dispatch_Fifo'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist", Test_Dispatch_Persist'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn", Test_Dispatch_Synchronous_Dyn'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise", Test_Dispatch_Synchronous_Raise'Access); end Add_Tests; package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Action_Bean, Method => Event_Action, Name => "send"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "priority" then From.Priority := Util.Beans.Objects.To_Integer (Value); elsif Name = "raise_exception" then From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value); end if; end Set_Value; overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; Action_Exception : exception; Global_Counter : Util.Concurrent.Counters.Counter; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); begin if From.Raise_Exception then raise Action_Exception with "Raising an exception from the event action bean"; end if; From.Count := From.Count + 1; Util.Concurrent.Counters.Increment (Global_Counter); end Event_Action; function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Action_Bean_Access := new Action_Bean; begin return Result.all'Access; end Create_Action_Bean; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test the Get_Event_Type_Name internal operation. -- ------------------------------ procedure Test_Get_Event_Name (T : in out Test) is begin Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all, "Get_Event_Type_Name"); end Test_Get_Event_Name; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; begin Manager.Initialize (App.all'Access); T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Action : constant EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Queue : Queue_Ref; Index : constant Event_Index := Find_Event_Index ("event-test-4"); begin Manager.Initialize (App.all'Access); Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx); Manager.Add_Queue (Queue); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => Queue, Action => Action, Params => Props); Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length), "Add_Action failed"); end loop; end Test_Add_Action; -- ------------------------------ -- Test dispatching events -- ------------------------------ procedure Dispatch_Event (T : in out Test; Kind : in Event_Index; Expect_Count : in Natural; Expect_Prio : in Natural) is Factory : AWA.Applications.Factory.Application_Factory; Conf : ASF.Applications.Config; Ctx : aliased EL.Contexts.Default.Default_Context; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml"); Action : aliased Action_Bean; begin Conf.Set ("database", Util.Tests.Get_Parameter ("database")); declare App : aliased AWA.Tests.Test_Application; S : Util.Measures.Stamp; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; SC : AWA.Services.Contexts.Service_Context; begin App.Initialize (Conf => Conf, Factory => Factory); App.Set_Global ("event_test", Util.Beans.Objects.To_Object (Action'Unchecked_Access, Util.Beans.Objects.STATIC)); SC.Set_Context (App'Unchecked_Access, null); App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Register_Class ("AWA.Events.Tests.Event_Action", Create_Action_Bean'Access); AWA.Applications.Configs.Read_Configuration (App => App, File => Path, Context => Ctx'Unchecked_Access, Override_Context => True); Util.Measures.Report (S, "Initialize AWA application and read config"); App.Start; Util.Measures.Report (S, "Start event tasks"); for I in 1 .. 100 loop declare Event : Module_Event; begin Event.Set_Event_Kind (Kind); Event.Set_Parameter ("prio", "3"); Event.Set_Parameter ("template", "def"); App.Send_Event (Event); end; end loop; Util.Measures.Report (S, "Send 100 events"); -- Wait for the dispatcher to process the events but do not wait more than 10 secs. for I in 1 .. 10_000 loop exit when Action.Count = Expect_Count; delay 0.1; end loop; end; Log.Info ("Action count: {0}", Natural'Image (Action.Count)); Log.Info ("Priority: {0}", Integer'Image (Action.Priority)); Util.Tests.Assert_Equals (T, Expect_Count, Action.Count, "invalid number of calls for the action (global bean)"); Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority, "prio parameter not transmitted (global bean)"); end Dispatch_Event; -- ------------------------------ -- Test dispatching synchronous event to a global bean. -- ------------------------------ procedure Test_Dispatch_Synchronous (T : in out Test) is begin T.Dispatch_Event (Event_Test_1.Kind, 500, 3); end Test_Dispatch_Synchronous; -- ------------------------------ -- Test dispatching event through a fifo queue. -- ------------------------------ procedure Test_Dispatch_Fifo (T : in out Test) is begin T.Dispatch_Event (Event_Test_2.Kind, 200, 3); end Test_Dispatch_Fifo; -- ------------------------------ -- Test dispatching event through a database queue. -- ------------------------------ procedure Test_Dispatch_Persist (T : in out Test) is begin T.Dispatch_Event (Event_Test_5.Kind, 100, 3); end Test_Dispatch_Persist; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean (created on demand). -- ------------------------------ procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is begin T.Dispatch_Event (Event_Test_3.Kind, 0, 0); end Test_Dispatch_Synchronous_Dyn; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean and raise an exception in the action. -- ------------------------------ procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is begin T.Dispatch_Event (Event_Test_4.Kind, 0, 0); end Test_Dispatch_Synchronous_Raise; end AWA.Events.Services.Tests;
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012, 2015, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Util.Concurrent.Counters; with EL.Beans; with EL.Expressions; with EL.Contexts.Default; with ASF.Applications; with ASF.Servlets.Faces; with AWA.Applications; with AWA.Applications.Configs; with AWA.Applications.Factory; with AWA.Events.Action_Method; with AWA.Services.Contexts; with AWA.Events.Queues; with AWA.Events.Services; package body AWA.Events.Services.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests"); package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name", Test_Get_Event_Name'Access); Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous", Test_Dispatch_Synchronous'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo", Test_Dispatch_Fifo'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist", Test_Dispatch_Persist'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn", Test_Dispatch_Synchronous_Dyn'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise", Test_Dispatch_Synchronous_Raise'Access); end Add_Tests; package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Action_Bean, Method => Event_Action, Name => "send"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "priority" then From.Priority := Util.Beans.Objects.To_Integer (Value); elsif Name = "raise_exception" then From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value); end if; end Set_Value; overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; Action_Exception : exception; Global_Counter : Util.Concurrent.Counters.Counter; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); begin if From.Raise_Exception then raise Action_Exception with "Raising an exception from the event action bean"; end if; From.Count := From.Count + 1; Util.Concurrent.Counters.Increment (Global_Counter); end Event_Action; function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Action_Bean_Access := new Action_Bean; begin return Result.all'Access; end Create_Action_Bean; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test the Get_Event_Type_Name internal operation. -- ------------------------------ procedure Test_Get_Event_Name (T : in out Test) is begin Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all, "Get_Event_Type_Name"); end Test_Get_Event_Name; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; begin Manager.Initialize (App.all'Access); T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Action : constant EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Queue : Queue_Ref; Index : constant Event_Index := Find_Event_Index ("event-test-4"); begin Manager.Initialize (App.all'Access); Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx); Manager.Add_Queue (Queue); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => Queue, Action => Action, Params => Props); Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length), "Add_Action failed"); end loop; end Test_Add_Action; -- ------------------------------ -- Test dispatching events -- ------------------------------ procedure Dispatch_Event (T : in out Test; Kind : in Event_Index; Expect_Count : in Natural; Expect_Prio : in Natural) is Factory : AWA.Applications.Factory.Application_Factory; Conf : ASF.Applications.Config; Ctx : aliased EL.Contexts.Default.Default_Context; Path : constant String := Util.Tests.Get_Path ("regtests/config/event-test.xml"); Action : aliased Action_Bean; begin Conf.Set ("database", Util.Tests.Get_Parameter ("database")); declare App : aliased AWA.Tests.Test_Application; S : Util.Measures.Stamp; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; SC : AWA.Services.Contexts.Service_Context; begin App.Initialize (Conf => Conf, Factory => Factory); App.Set_Global ("event_test", Util.Beans.Objects.To_Object (Action'Unchecked_Access, Util.Beans.Objects.STATIC)); SC.Set_Context (App'Unchecked_Access, null); App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Register_Class ("AWA.Events.Tests.Event_Action", Create_Action_Bean'Access); AWA.Applications.Configs.Read_Configuration (App => App, File => Path, Context => Ctx'Unchecked_Access, Override_Context => True); Util.Measures.Report (S, "Initialize AWA application and read config"); App.Start; Util.Measures.Report (S, "Start event tasks"); for I in 1 .. 100 loop declare Event : Module_Event; begin Event.Set_Event_Kind (Kind); Event.Set_Parameter ("prio", "3"); Event.Set_Parameter ("template", "def"); App.Send_Event (Event); end; end loop; Util.Measures.Report (S, "Send 100 events"); -- Wait for the dispatcher to process the events but do not wait more than 10 secs. for I in 1 .. 10_000 loop exit when Action.Count = Expect_Count; delay 0.1; end loop; end; Log.Info ("Action count: {0}", Natural'Image (Action.Count)); Log.Info ("Priority: {0}", Integer'Image (Action.Priority)); Util.Tests.Assert_Equals (T, Expect_Count, Action.Count, "invalid number of calls for the action (global bean)"); Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority, "prio parameter not transmitted (global bean)"); end Dispatch_Event; -- ------------------------------ -- Test dispatching synchronous event to a global bean. -- ------------------------------ procedure Test_Dispatch_Synchronous (T : in out Test) is begin T.Dispatch_Event (Event_Test_1.Kind, 500, 3); end Test_Dispatch_Synchronous; -- ------------------------------ -- Test dispatching event through a fifo queue. -- ------------------------------ procedure Test_Dispatch_Fifo (T : in out Test) is begin T.Dispatch_Event (Event_Test_2.Kind, 200, 3); end Test_Dispatch_Fifo; -- ------------------------------ -- Test dispatching event through a database queue. -- ------------------------------ procedure Test_Dispatch_Persist (T : in out Test) is begin T.Dispatch_Event (Event_Test_5.Kind, 100, 3); end Test_Dispatch_Persist; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean (created on demand). -- ------------------------------ procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is begin T.Dispatch_Event (Event_Test_3.Kind, 0, 0); end Test_Dispatch_Synchronous_Dyn; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean and raise an exception in the action. -- ------------------------------ procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is begin T.Dispatch_Event (Event_Test_4.Kind, 0, 0); end Test_Dispatch_Synchronous_Raise; end AWA.Events.Services.Tests;
Replace Util.Tests.Get_Test_Path by Util.Tests.Get_Path
Replace Util.Tests.Get_Test_Path by Util.Tests.Get_Path
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
721a45ab8dadeb1104a718acec64e1398769fc14
src/asf-security-filters-oauth.ads
src/asf-security-filters-oauth.ads
----------------------------------------------------------------------- -- security-filters-oauth -- OAuth Security filter -- 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 ASF.Filters; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with Security.OAuth.Servers; use Security.OAuth; with Security.Policies; -- The <b>ASF.Security.Filters.OAuth</b> package provides a servlet filter that -- implements the RFC 6749 "Accessing Protected Resources" part: it extracts the OAuth -- access token, verifies the grant and the permission. The servlet filter implements -- the RFC 6750 "OAuth 2.0 Bearer Token Usage". -- package ASF.Security.Filters.OAuth is -- RFC 2617 HTTP header for authorization. AUTHORIZATION_HEADER_NAME : constant String := "Authorization"; -- RFC 2617 HTTP header for failed authorization. WWW_AUTHENTICATE_HEADER_NAME : constant String := "WWW-Authenticate"; type Auth_Filter is new ASF.Filters.Filter with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- Set the permission manager that must be used to verify the permission. procedure Set_Permission_Manager (Filter : in out Auth_Filter; Manager : in Policies.Policy_Manager_Access); -- Filter the request to make sure the user is authenticated. -- Invokes the <b>Do_Login</b> procedure if there is no user. -- If a permission manager is defined, check that the user has the permission -- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission -- is denied. procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. procedure Do_Login (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Display the forbidden access page. This procedure is called when the user is not -- authorized to see the page. The default implementation returns the SC_FORBIDDEN error. procedure Do_Deny (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); private type Auth_Filter is new ASF.Filters.Filter with record Manager : Policies.Policy_Manager_Access; Realm : Servers.Auth_Manager_Access; Realm_URL : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Security.Filters.OAuth;
----------------------------------------------------------------------- -- security-filters-oauth -- OAuth Security filter -- 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 ASF.Filters; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with Security.OAuth.Servers; use Security.OAuth; with Security.Policies; with Servlet.Security.Filters.OAuth; -- The <b>ASF.Security.Filters.OAuth</b> package provides a servlet filter that -- implements the RFC 6749 "Accessing Protected Resources" part: it extracts the OAuth -- access token, verifies the grant and the permission. The servlet filter implements -- the RFC 6750 "OAuth 2.0 Bearer Token Usage". -- package ASF.Security.Filters.OAuth renames Servlet.Security.Filters.OAuth;
Package ASF.Security.Filters moved to Servlet.Security.Filters
Package ASF.Security.Filters moved to Servlet.Security.Filters
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c216a997f2918eddb85b10fbf9752b2e923d9fd1
src/ado-c.adb
src/ado-c.adb
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.C is use Ada.Strings.Unbounded; use type Interfaces.C.Strings.chars_ptr; -- ------------------------------ -- Convert a string to a C string. -- ------------------------------ function To_String_Ptr (S : String) return String_Ptr is begin return Result : String_Ptr do Result.Ptr := Strings.New_String (S); end return; end To_String_Ptr; -- ------------------------------ -- Get the C string pointer. -- ------------------------------ function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr is begin return S.Ptr; end To_C; -- ------------------------------ -- Set the string -- ------------------------------ procedure Set_String (S : in out String_Ptr; Value : in String) is begin if S.Ptr /= Interfaces.C.Strings.Null_Ptr then Strings.Free (S.Ptr); end if; S.Ptr := Strings.New_String (Value); end Set_String; -- ------------------------------ -- Reclaim the storage held by the C string. -- ------------------------------ procedure Finalize (S : in out String_Ptr) is begin Strings.Free (S.Ptr); end Finalize; end ADO.C;
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.C is use type Interfaces.C.Strings.chars_ptr; -- ------------------------------ -- Convert a string to a C string. -- ------------------------------ function To_String_Ptr (S : String) return String_Ptr is begin return Result : String_Ptr do Result.Ptr := Strings.New_String (S); end return; end To_String_Ptr; -- ------------------------------ -- Get the C string pointer. -- ------------------------------ function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr is begin return S.Ptr; end To_C; -- ------------------------------ -- Set the string -- ------------------------------ procedure Set_String (S : in out String_Ptr; Value : in String) is begin if S.Ptr /= Interfaces.C.Strings.Null_Ptr then Strings.Free (S.Ptr); end if; S.Ptr := Strings.New_String (Value); end Set_String; -- ------------------------------ -- Reclaim the storage held by the C string. -- ------------------------------ procedure Finalize (S : in out String_Ptr) is begin Strings.Free (S.Ptr); end Finalize; end ADO.C;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
f4cbc2783c415d7f86be5733f40bc89df02c1fc7
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise Session_Error; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal operation to get access to the database connection. -- ------------------------------ procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)) is begin Check_Session (Database); Process (Database.Impl.Database.Value.all); end Access_Connection; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ado-sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise Session_Error; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Get the audit manager. -- ------------------------------ function Get_Audit_Manager (Database : in Master_Session) return access Audits.Audit_Manager'Class is begin return Database.Audit; end Get_Audit_Manager; -- ------------------------------ -- Internal operation to get access to the database connection. -- ------------------------------ procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)) is begin Check_Session (Database); Process (Database.Impl.Database.Value.all); end Access_Connection; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Implement the Get_Audit_Manager function
Implement the Get_Audit_Manager function
Ada
apache-2.0
stcarrez/ada-ado
fd7f17e690dfc2f4b61e5a2d10c703d3d8c95385
awa/awaunit/awa-tests-helpers.adb
awa/awaunit/awa-tests-helpers.adb
----------------------------------------------------------------------- -- awa-tests-helpers - Helpers for AWA unit tests -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; package body AWA.Tests.Helpers is -- ------------------------------ -- Extract from the Location header the part that is after the given base string. -- If the Location header does not start with the base string, returns the empty -- string. -- ------------------------------ function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return String is R : constant String := Reply.Get_Header ("Location"); begin if R'Length < Base'Length then return ""; elsif R (R'First .. R'First + Base'Length - 1) /= Base then return ""; else return R (R'First + Base'Length .. R'Last); end if; end Extract_Redirect; function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Extract_Redirect (Reply, Base)); end Extract_Redirect; -- ------------------------------ -- Extract from the response content a link with a given title. -- ------------------------------ function Extract_Link (Content : in String; Title : in String) return String is use GNAT.Regpat; Pattern : constant String := " href=""([a-zA-Z0-9/]+)"">" & Title & "</a>"; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern); Result : GNAT.Regpat.Match_Array (0 .. 1); begin Match (Regexp, Content, Result); if Result (1) = GNAT.Regpat.No_Match then return ""; end if; return Content (Result (1).First .. Result (1).Last); end Extract_Link; end AWA.Tests.Helpers;
----------------------------------------------------------------------- -- awa-tests-helpers - Helpers for AWA unit tests -- Copyright (C) 2011, 2017, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; package body AWA.Tests.Helpers is -- ------------------------------ -- Extract from the Location header the part that is after the given base string. -- If the Location header does not start with the base string, returns the empty -- string. -- ------------------------------ function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return String is R : constant String := Reply.Get_Header ("Location"); begin if R'Length < Base'Length then return ""; elsif R (R'First .. R'First + Base'Length - 1) /= Base then return ""; else return R (R'First + Base'Length .. R'Last); end if; end Extract_Redirect; function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Extract_Redirect (Reply, Base)); end Extract_Redirect; -- ------------------------------ -- Extract from the response content a link with a given title. -- ------------------------------ function Extract_Link (Content : in String; Title : in String) return String is use GNAT.Regpat; Pattern : constant String := " href=""([a-zA-Z0-9/]+)"">" & Title & "</a>"; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern); Result : GNAT.Regpat.Match_Array (0 .. 1); begin Match (Regexp, Content, Result); if Result (1) = GNAT.Regpat.No_Match then return ""; end if; return Content (Result (1).First .. Result (1).Last); end Extract_Link; -- ------------------------------ -- Extract from the response content an HTML identifier that was generated -- with the given prefix. The format is assumed to be <prefix>-<number>. -- ------------------------------ function Extract_Identifier (Content : in String; Prefix : in String) return ADO.Identifier is use GNAT.Regpat; Pattern : constant String := ".*[\\""']" & Prefix & "\-([0-9]+)[\\""']"; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern); Result : GNAT.Regpat.Match_Array (0 .. 1); begin Match (Regexp, Content, Result); if Result (1) = GNAT.Regpat.No_Match then return ADO.NO_IDENTIFIER; end if; return ADO.Identifier'Value (Content (Result (1).First .. Result (1).Last)); exception when Constraint_Error => return ADO.NO_IDENTIFIER; end Extract_Identifier; end AWA.Tests.Helpers;
Implement new function Extract_Identifier
Implement new function Extract_Identifier
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a51bbdf21923c5524d6780539b17863a67defb91
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
Add the Get_Parameter function to the Generator interface
Add the Get_Parameter function to the Generator interface
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
0eb4ba67ec446491762a7585edc41d072177fc12
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ overriding procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Preformatted (Text, Format); end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Filter_Type) is begin Document.Document.Finish; end Finish; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Filter_Type) is begin Document.Document.Finish; end Finish; end Wiki.Filters;
Update the Add_Preformatted procedure
Update the Add_Preformatted procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
dfb20b1fdeb9924df4327fbae57ed7d65686435d
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_TABLE, N_ROW, N_COLUMN, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record Parent : Node_Type_Access; case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
Add support for wiki tables - Add N_TABLE, N_ROW, N_COL and make Parent accessible for all kinds in the Node_Type
Add support for wiki tables - Add N_TABLE, N_ROW, N_COL and make Parent accessible for all kinds in the Node_Type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bda5aee6cc5726ad5c495edb951cfdfc266c0115
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); end Wiki.Parsers;
Declare the Flush_Text procedure in the package private specification part
Declare the Flush_Text procedure in the package private specification part
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b54f6e11d4055acd6fb27787240dd3b7f53ce60f
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Update to use Get_Location and Set_Name
Update to use Get_Location and Set_Name
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
09933ccb1f6159190a2319aaad6c36ae31cd3131
tests/natools-smaz-tests.adb
tests/natools-smaz-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Strings.Unbounded; with Natools.Smaz.Original; package body Natools.Smaz.Tests is function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Roundtrip_Test (Test : in out NT.Test; Dict : in Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Image; procedure Roundtrip_Test (Test : in out NT.Test; Dict : in Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; Buffer : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Decompressed) + 10); Last : Ada.Streams.Stream_Element_Offset; Done : Boolean := False; begin begin Compress (Dict, Decompressed, Buffer, Last); Done := True; exception when Error : others => Test.Info ("During compression of """ & Decompressed & '"'); Test.Report_Exception (Error, NT.Fail); end; if Done and then Buffer (1 .. Last) /= Compressed then Test.Fail ("Compression of """ & Decompressed & """ failed"); Test.Info ("Found: " & Image (Buffer (1 .. Last))); Test.Info ("Expected:" & Image (Compressed)); end if; declare Buffer_2 : String (1 .. Decompressed_Length (Dict, Buffer (1 .. Last))); Last_2 : Natural; Done : Boolean := False; begin begin Decompress (Dict, Compressed, Buffer_2, Last_2); Done := True; exception when Error : others => Test.Info ("During compression of """ & Decompressed & '"'); Test.Report_Exception (Error, NT.Fail); end; if Done and then Buffer_2 (1 .. Last_2) /= Decompressed then Test.Fail ("Roundtrip for """ & Decompressed & """ failed"); Test.Info ("Found """ & Buffer_2 (1 .. Last_2) & '"'); end if; end; end Roundtrip_Test; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Sample_Strings (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Sample_Strings (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 1, 48, 48, 24, 204, 254, 69, 250, 4, 45, 60, 22, 255, 2, 51, 51, 51)); Roundtrip_Test (Test, Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 1, 49, 48, 0, 255, 1, 50, 48, 0, 255, 1, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings; end Natools.Smaz.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Strings.Unbounded; with Natools.Smaz.Original; package body Natools.Smaz.Tests is function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Roundtrip_Test (Test : in out NT.Test; Dict : in Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Image; procedure Roundtrip_Test (Test : in out NT.Test; Dict : in Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; Buffer : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Decompressed) + 10); Last : Ada.Streams.Stream_Element_Offset; Done : Boolean := False; begin begin Compress (Dict, Decompressed, Buffer, Last); Done := True; exception when Error : others => Test.Info ("During compression of """ & Decompressed & '"'); Test.Report_Exception (Error, NT.Fail); end; if Done and then Buffer (1 .. Last) /= Compressed then Test.Fail ("Compression of """ & Decompressed & """ failed"); Test.Info ("Found: " & Image (Buffer (1 .. Last))); Test.Info ("Expected:" & Image (Compressed)); end if; declare Buffer_2 : String (1 .. Decompressed_Length (Dict, Buffer (1 .. Last))); Last_2 : Natural; Done : Boolean := False; begin begin Decompress (Dict, Buffer (1 .. Last), Buffer_2, Last_2); Done := True; exception when Error : others => Test.Info ("During compression of """ & Decompressed & '"'); Test.Report_Exception (Error, NT.Fail); end; if Done and then Buffer_2 (1 .. Last_2) /= Decompressed then Test.Fail ("Roundtrip for """ & Decompressed & """ failed"); Test.Info ("Found """ & Buffer_2 (1 .. Last_2) & '"'); end if; end; end Roundtrip_Test; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Sample_Strings (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Sample_Strings (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 1, 48, 48, 24, 204, 254, 69, 250, 4, 45, 60, 22, 255, 2, 51, 51, 51)); Roundtrip_Test (Test, Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 1, 49, 48, 0, 255, 1, 50, 48, 0, 255, 1, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings; end Natools.Smaz.Tests;
make round-trip test really a round-trip
smaz-tests: make round-trip test really a round-trip Since there are multiple encoded sequence that decompress into the same original string, it is much more important to check that compressed data really decompress into the original data than to check that it matches exactly the expected byte sequence
Ada
isc
faelys/natools
5aa2f3da31e6d24887d1f73a6b0802174adadc65
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
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
9f9309d61c26f182ab789caa6165f64afbf51098
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- 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) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- 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_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_WString (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_Index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- 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) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- 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) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Render (Doc, Node.Content); Engine.Add_Line_Break; Engine.Has_Paragraph := False; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- 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) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- 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_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_WString (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_Index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- 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) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- 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) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Render (Doc, Node.Content); Engine.Add_Line_Break; Engine.Has_Paragraph := False; Engine.Empty_Line := False; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
Make sure to emite a newline after the header line
Make sure to emite a newline after the header line
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b8c2ac68d7c43604d358883e5813a611bbf850cd
services/src/filesystems/partitions.ads
services/src/filesystems/partitions.ads
with HAL; use HAL; with HAL.Block_Drivers; use HAL.Block_Drivers; with Interfaces; use Interfaces; package Partitions is type Partition_Kind is (Empty_Partition, Fat12_Parition, Fat16_Parition, Extended_Parition, Fat16B_Parition, NTFS_Partition, Fat32_CHS_Parition, Fat32_LBA_Parition, Fat16B_LBA_Parition, Extended_LBA_Parition, Linux_Partition) with Size => 8; subtype Logical_Block_Address is Unsigned_32; type CHS_Address is record C : UInt10; H : Byte; S : UInt6; end record with Pack, Size => 24; type Partition_Entry is record Status : Byte; First_Sector_CHS : CHS_Address; Kind : Partition_Kind; Last_Sector_CHS : CHS_Address; First_Sector_LBA : Logical_Block_Address; Number_Of_Sectors : Unsigned_32; end record with Pack, Size => 16 * 8; type Status_Code is (Status_Ok, Disk_Error, Invalid_Parition); function Get_Partition_Entry (Disk : not null Block_Driver_Ref; Entry_Number : Positive; P_Entry : out Partition_Entry) return Status_Code; function Number_Of_Partitions (Disk : Block_Driver_Ref) return Natural; function Is_Valid (P_Entry : Partition_Entry) return Boolean is (P_Entry.Status = 16#00# or else P_Entry.Status = 16#80#); private for Partition_Kind use (Empty_Partition => 16#00#, Fat12_Parition => 16#01#, Fat16_Parition => 16#04#, Extended_Parition => 16#05#, Fat16B_Parition => 16#06#, NTFS_Partition => 16#07#, Fat32_CHS_Parition => 16#0B#, Fat32_LBA_Parition => 16#0C#, Fat16B_LBA_Parition => 16#0E#, Extended_LBA_Parition => 16#0F#, Linux_Partition => 16#83#); end Partitions;
with HAL; use HAL; with HAL.Block_Drivers; use HAL.Block_Drivers; with Interfaces; use Interfaces; package Partitions is type Partition_Kind is new Unsigned_8; Empty_Partition : constant Partition_Kind := 16#00#; Fat12_Parition : constant Partition_Kind := 16#01#; Fat16_Parition : constant Partition_Kind := 16#04#; Extended_Parition : constant Partition_Kind := 16#05#; Fat16B_Parition : constant Partition_Kind := 16#06#; NTFS_Partition : constant Partition_Kind := 16#07#; Fat32_CHS_Parition : constant Partition_Kind := 16#0B#; Fat32_LBA_Parition : constant Partition_Kind := 16#0C#; Fat16B_LBA_Parition : constant Partition_Kind := 16#0E#; Extended_LBA_Parition : constant Partition_Kind := 16#0F#; Linux_Swap_Partition : constant Partition_Kind := 16#82#; Linux_Partition : constant Partition_Kind := 16#83#; subtype Logical_Block_Address is Unsigned_32; type CHS_Address is record C : UInt10; H : Byte; S : UInt6; end record with Pack, Size => 24; type Partition_Entry is record Status : Byte; First_Sector_CHS : CHS_Address; Kind : Partition_Kind; Last_Sector_CHS : CHS_Address; First_Sector_LBA : Logical_Block_Address; Number_Of_Sectors : Unsigned_32; end record with Pack, Size => 16 * 8; type Status_Code is (Status_Ok, Disk_Error, Invalid_Parition); function Get_Partition_Entry (Disk : not null Block_Driver_Ref; Entry_Number : Positive; P_Entry : out Partition_Entry) return Status_Code; function Number_Of_Partitions (Disk : Block_Driver_Ref) return Natural; function Is_Valid (P_Entry : Partition_Entry) return Boolean is (P_Entry.Status = 16#00# or else P_Entry.Status = 16#80#); end Partitions;
Change Parition_Kind to Unsigned_8
Partitions: Change Parition_Kind to Unsigned_8 Enum would be better but it means we have to give a name to all 256 possible values.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library
77deacc62ae205c1d50ae6515daea7ae0a8dc534
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is -- procedure Free is -- new Ada.Unchecked_Deallocation (Object => Attribute, -- Name => Attribute_Access); -- Item : Attribute_Access; begin -- while not List.List.Is_Empty loop -- Item := List.List.Last_Element; -- List.List.Delete_Last; -- Free (Item); -- end loop; List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is -- procedure Free is -- new Ada.Unchecked_Deallocation (Object => Attribute, -- Name => Attribute_Access); -- Item : Attribute_Access; begin -- while not List.List.Is_Empty loop -- Item := List.List.Last_Element; -- List.List.Delete_Last; -- Free (Item); -- end loop; List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
Implement Get_Attribute
Implement Get_Attribute
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c807f6411a375b412320be068b8c6215d05b4964
Ada/src/Problem_69.adb
Ada/src/Problem_69.adb
with Ada.Text_IO; with PrimeUtilities; package body Problem_69 is package IO renames Ada.Text_IO; subtype One_Million is Integer range 1 .. 1_000_000; best : One_Million := 1; package Million_Primes is new PrimeUtilities(One_Million); procedure Solve is prime : One_Million; gen : Million_Primes.Prime_Generator := Million_Primes.Make_Generator(One_Million'Last); begin loop Million_Primes.Next_Prime(gen, prime); exit when prime = 1; exit when One_Million'Last / prime < best; best := best * prime; end loop; IO.Put_Line(Integer'Image(best)); end Solve; end Problem_69;
with Ada.Text_IO; with PrimeUtilities; package body Problem_69 is package IO renames Ada.Text_IO; subtype One_Million is Integer range 1 .. 1_000_000; best : One_Million := 1; package Million_Primes is new PrimeUtilities(One_Million); procedure Solve is prime : One_Million; gen : Million_Primes.Prime_Generator := Million_Primes.Make_Generator(One_Million'Last); begin -- The Euler number can be calculated by multiplying together the percent of the numbers that -- each prime factor of the number will remove. Since we're scaling by the number itself -- getting bigger numbers will not help us, just a larger percent of numbers filtered. Each -- prime factor will filter out 1/p of the numbers in the number line, leaving p-1/p -- remaining. So the smaller the primes we can pick, the larger the percent of numbers we will -- filter out. And since we're picking the smallest primes, we know we could never pick more -- larger primes and end up with a smaller end target (because we could replace the larger -- prime with a smaller prime, get a better ratio). As a result we can just multiply from the -- smallest prime number upwards until we get above our maximum ratio. loop Million_Primes.Next_Prime(gen, prime); exit when prime = 1; exit when One_Million'Last / prime < best; best := best * prime; end loop; IO.Put_Line(Integer'Image(best)); end Solve; end Problem_69;
Add comment as to why the multiply smallest primes works for that problem that I thought through on my run yesterday morning.
Add comment as to why the multiply smallest primes works for that problem that I thought through on my run yesterday morning.
Ada
unlicense
Tim-Tom/project-euler,Tim-Tom/project-euler,Tim-Tom/project-euler
5eb250aa869bbb4a76259e37d3f145c6a2ff01df
src/ado.ads
src/ado.ads
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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 Ada.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); end ADO;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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 Ada.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); end ADO;
Define the "=" function operator for the Nullable_Time type
Define the "=" function operator for the Nullable_Time type
Ada
apache-2.0
stcarrez/ada-ado
52aa1f3386fd741c8551eca8d0fec74b27ee3438
awa/plugins/awa-images/src/awa-images-modules.adb
awa/plugins/awa-images/src/awa-images-modules.adb
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 2012, 2016, 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.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with EL.Variables.Default; with EL.Contexts.Default; with AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with AWA.Services.Contexts; with AWA.Modules.Beans; with AWA.Images.Beans; package body AWA.Images.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); package Register is new AWA.Modules.Beans (Module => Image_Module, Module_Access => Image_Module_Access); -- ------------------------------ -- Job worker procedure to identify an image and generate its thumnbnail. -- ------------------------------ procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Module : constant Image_Module_Access := Get_Image_Module; begin Module.Do_Thumbnail_Job (Job); end Thumbnail_Worker; -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_List_Bean", Handler => AWA.Images.Beans.Create_Image_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_Bean", Handler => AWA.Images.Beans.Create_Image_Bean'Access); App.Add_Servlet ("image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having -- read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); use type AWA.Jobs.Modules.Job_Module_Access; begin Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; if Plugin.Job_Module = null then Log.Error ("Cannot find the AWA Job module for the image thumbnail generation"); else Plugin.Job_Module.Register (Definition => Thumbnail_Job_Definition.Factory); end if; Plugin.Thumbnail_Command := Plugin.Get_Config (PARAM_THUMBNAIL_COMMAND); end Configure; -- ------------------------------ -- Create a thumbnail job for the image. -- ------------------------------ procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("image_id", Image); J.Schedule (Thumbnail_Job_Definition.Factory.all); end Make_Thumbnail_Job; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- Create an image instance. -- ------------------------------ procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin if File.Get_Original.Is_Null then declare Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Plugin.Make_Thumbnail_Job (Img); end; end if; end Create_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify -- the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify -- the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); else Image_Module'Class (Instance).Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify -- the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Image_Module'Class (Instance).Delete_Image (Item); end On_Delete; -- ------------------------------ -- Thumbnail job to identify the image dimension and produce a thumbnail. -- ------------------------------ procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Image_Id : constant ADO.Identifier := Job.Get_Parameter ("image_id"); begin Image_Module'Class (Plugin).Build_Thumbnail (Image_Id); end Do_Thumbnail_Job; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; procedure Create_Thumbnail (Service : in Image_Module; Source : in String; Into : in String; Width : in out Natural; Height : in 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)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information -- about the original image. Extract the picture width and -- height. -- image.png PNG 120x282 120x282+0+0 8-bit \ -- DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Module; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one -- of the following formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then begin Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); exception when Constraint_Error => Width := 0; end; else Width := 0; end if; if Pos < Dimension'Last then begin Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); exception when Constraint_Error => Height := 0; end; else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Modules;
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 2012, 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 Ada.Strings.Unbounded; with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with EL.Variables.Default; with EL.Contexts.Default; with AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with AWA.Services.Contexts; with AWA.Modules.Beans; with AWA.Images.Beans; package body AWA.Images.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); package Register is new AWA.Modules.Beans (Module => Image_Module, Module_Access => Image_Module_Access); -- ------------------------------ -- Job worker procedure to identify an image and generate its thumnbnail. -- ------------------------------ procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Module : constant Image_Module_Access := Get_Image_Module; begin Module.Do_Thumbnail_Job (Job); end Thumbnail_Worker; -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_List_Bean", Handler => AWA.Images.Beans.Create_Image_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_Bean", Handler => AWA.Images.Beans.Create_Image_Bean'Access); App.Add_Servlet ("image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having -- read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); use type AWA.Jobs.Modules.Job_Module_Access; begin Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; if Plugin.Job_Module = null then Log.Error ("Cannot find the AWA Job module for the image thumbnail generation"); else Plugin.Job_Module.Register (Definition => Thumbnail_Job_Definition.Factory); end if; Plugin.Thumbnail_Command := Plugin.Get_Config (PARAM_THUMBNAIL_COMMAND); end Configure; -- ------------------------------ -- Create a thumbnail job for the image. -- ------------------------------ procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("image_id", Image); J.Schedule (Thumbnail_Job_Definition.Factory.all); end Make_Thumbnail_Job; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- Create an image instance. -- ------------------------------ procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin if File.Get_Original.Is_Null then declare Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Plugin.Make_Thumbnail_Job (Img); end; end if; end Create_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify -- the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify -- the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); else Image_Module'Class (Instance).Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify -- the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Image_Module'Class (Instance).Delete_Image (Item); end On_Delete; -- ------------------------------ -- Thumbnail job to identify the image dimension and produce a thumbnail. -- ------------------------------ procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Image_Id : constant ADO.Identifier := Job.Get_Parameter ("image_id"); begin Image_Module'Class (Plugin).Build_Thumbnail (Image_Id); end Do_Thumbnail_Job; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; procedure Create_Thumbnail (Service : in Image_Module; Source : in String; Into : in String; Width : in out Natural; Height : in 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)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information -- about the original image. Extract the picture width and -- height. -- image.png PNG 120x282 120x282+0+0 8-bit \ -- DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and then 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 then Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Module; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or else To_Height = Natural'Last or else (To_Width = 0 and then To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one -- of the following formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then begin Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); exception when Constraint_Error => Width := 0; end; else Width := 0; end if; if Pos < Dimension'Last then begin Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); exception when Constraint_Error => Height := 0; end; else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Modules;
Fix style warnings: add missing overriding and update and then/or else conditions
Fix style warnings: add missing overriding and update and then/or else conditions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b474166df879b452873d9e50e9292498b7ba711f
mat/src/matp.adb
mat/src/matp.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; begin Target.Console (Console'Unchecked_Access); Target.Initialize_Options; MAT.Commands.Initialize_Files (Target); Server.Start (Options.Address); MAT.Commands.Interactive (Target); Server.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error => Server.Stop; end Matp;
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; begin Target.Console (Console'Unchecked_Access); Target.Initialize_Options; MAT.Commands.Initialize_Files (Target); Target.Start; MAT.Commands.Interactive (Target); Server.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error => Server.Stop; end Matp;
Update to call the target Start procedure
Update to call the target Start procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9cb9fc0bd9f277881fd65b0abf47c1ec51cd4ab0
components/src/screen/ssd1306/ssd1306.adb
components/src/screen/ssd1306/ssd1306.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package body SSD1306 is procedure Write_Command (This : SSD1306_Screen; Cmd : UInt8); procedure Write_Data (This : SSD1306_Screen; Data : UInt8_Array); ------------------- -- Write_Command -- ------------------- procedure Write_Command (This : SSD1306_Screen; Cmd : UInt8) is Status : I2C_Status; begin This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr, Data => (1 => 0, 2 => (Cmd)), Status => Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; end Write_Command; ---------------- -- Write_Data -- ---------------- procedure Write_Data (This : SSD1306_Screen; Data : UInt8_Array) is Status : I2C_Status; begin This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr, Data => Data, Status => Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; end Write_Data; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out SSD1306_Screen; External_VCC : Boolean) is begin if This.Width * This.Height /= (This.Buffer_Size_In_Byte * 8) then raise Program_Error with "Invalid screen parameters"; end if; This.RST.Clear; This.Time.Delay_Milliseconds (100); This.RST.Set; This.Time.Delay_Milliseconds (100); Write_Command (This, DISPLAY_OFF); Write_Command (This, SET_DISPLAY_CLOCK_DIV); Write_Command (This, 16#80#); Write_Command (This, SET_MULTIPLEX); Write_Command (This, UInt8 (This.Height - 1)); Write_Command (This, SET_DISPLAY_OFFSET); Write_Command (This, 16#00#); Write_Command (This, SET_START_LINE or 0); Write_Command (This, CHARGE_PUMP); Write_Command (This, (if External_VCC then 16#10# else 16#14#)); Write_Command (This, MEMORY_MODE); Write_Command (This, 16#00#); Write_Command (This, SEGREMAP or 1); Write_Command (This, COM_SCAN_DEC); Write_Command (This, SET_COMPINS); Write_Command (This, 16#02#); Write_Command (This, SET_CONTRAST); Write_Command (This, 16#AF#); Write_Command (This, SET_PRECHARGE); Write_Command (This, (if External_VCC then 16#22# else 16#F1#)); Write_Command (This, SET_VCOM_DETECT); Write_Command (This, 16#40#); Write_Command (This, DISPLAY_ALL_ON_RESUME); Write_Command (This, NORMAL_DISPLAY); Write_Command (This, DEACTIVATE_SCROLL); This.Device_Initialized := True; end Initialize; ----------------- -- Initialized -- ----------------- overriding function Initialized (This : SSD1306_Screen) return Boolean is (This.Device_Initialized); ------------- -- Turn_On -- ------------- procedure Turn_On (This : SSD1306_Screen) is begin Write_Command (This, DISPLAY_ON); end Turn_On; -------------- -- Turn_Off -- -------------- procedure Turn_Off (This : SSD1306_Screen) is begin Write_Command (This, DISPLAY_OFF); end Turn_Off; -------------------------- -- Display_Inversion_On -- -------------------------- procedure Display_Inversion_On (This : SSD1306_Screen) is begin Write_Command (This, INVERT_DISPLAY); end Display_Inversion_On; --------------------------- -- Display_Inversion_Off -- --------------------------- procedure Display_Inversion_Off (This : SSD1306_Screen) is begin Write_Command (This, NORMAL_DISPLAY); end Display_Inversion_Off; ---------------------- -- Write_Raw_Pixels -- ---------------------- procedure Write_Raw_Pixels (This : SSD1306_Screen; Data : HAL.UInt8_Array) is begin Write_Command (This, COLUMN_ADDR); Write_Command (This, 0); -- from Write_Command (This, UInt8 (This.Width - 1)); -- to Write_Command (This, PAGE_ADDR); Write_Command (This, 0); -- from Write_Command (This, UInt8 (This.Height / 8) - 1); -- to Write_Data (This, (1 => 16#40#) & Data); end Write_Raw_Pixels; -------------------- -- Get_Max_Layers -- -------------------- overriding function Max_Layers (This : SSD1306_Screen) return Positive is (1); ------------------ -- Is_Supported -- ------------------ overriding function Supported (This : SSD1306_Screen; Mode : FB_Color_Mode) return Boolean is (Mode = HAL.Bitmap.RGB_565); --------------------- -- Set_Orientation -- --------------------- overriding procedure Set_Orientation (This : in out SSD1306_Screen; Orientation : Display_Orientation) is begin null; end Set_Orientation; -------------- -- Set_Mode -- -------------- overriding procedure Set_Mode (This : in out SSD1306_Screen; Mode : Wait_Mode) is begin null; end Set_Mode; --------------- -- Get_Width -- --------------- overriding function Width (This : SSD1306_Screen) return Positive is (This.Width); ---------------- -- Get_Height -- ---------------- overriding function Height (This : SSD1306_Screen) return Positive is (This.Height); ---------------- -- Is_Swapped -- ---------------- overriding function Swapped (This : SSD1306_Screen) return Boolean is (False); -------------------- -- Set_Background -- -------------------- overriding procedure Set_Background (This : SSD1306_Screen; R, G, B : UInt8) is begin -- Does it make sense when there's no alpha channel... raise Program_Error; end Set_Background; ---------------------- -- Initialize_Layer -- ---------------------- overriding procedure Initialize_Layer (This : in out SSD1306_Screen; Layer : Positive; Mode : FB_Color_Mode; X : Natural := 0; Y : Natural := 0; Width : Positive := Positive'Last; Height : Positive := Positive'Last) is pragma Unreferenced (X, Y, Width, Height); begin if Layer /= 1 or else Mode /= M_1 then raise Program_Error; end if; This.Memory_Layer.Actual_Width := This.Width; This.Memory_Layer.Actual_Height := This.Height; This.Memory_Layer.Addr := This.Memory_Layer.Data'Address; This.Memory_Layer.Actual_Color_Mode := Mode; This.Layer_Initialized := True; end Initialize_Layer; ----------------- -- Initialized -- ----------------- overriding function Initialized (This : SSD1306_Screen; Layer : Positive) return Boolean is begin return Layer = 1 and then This.Layer_Initialized; end Initialized; ------------------ -- Update_Layer -- ------------------ overriding procedure Update_Layer (This : in out SSD1306_Screen; Layer : Positive; Copy_Back : Boolean := False) is pragma Unreferenced (Copy_Back); begin if Layer /= 1 then raise Program_Error; end if; This.Write_Raw_Pixels (This.Memory_Layer.Data); end Update_Layer; ------------------- -- Update_Layers -- ------------------- overriding procedure Update_Layers (This : in out SSD1306_Screen) is begin This.Update_Layer (1); end Update_Layers; -------------------- -- Get_Color_Mode -- -------------------- overriding function Color_Mode (This : SSD1306_Screen; Layer : Positive) return FB_Color_Mode is pragma Unreferenced (This); begin if Layer /= 1 then raise Program_Error; end if; return M_1; end Color_Mode; ----------------------- -- Get_Hidden_Buffer -- ----------------------- overriding function Hidden_Buffer (This : in out SSD1306_Screen; Layer : Positive) return not null HAL.Bitmap.Any_Bitmap_Buffer is begin if Layer /= 1 then raise Program_Error; end if; return This.Memory_Layer'Unchecked_Access; end Hidden_Buffer; -------------------- -- Get_Pixel_Size -- -------------------- overriding function Pixel_Size (This : SSD1306_Screen; Layer : Positive) return Positive is (1); --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point) is X : constant Natural := Buffer.Width - 1 - Pt.X; Y : constant Natural := Buffer.Height - 1 - Pt.Y; Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width; Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index); begin if Buffer.Native_Source = 0 then Byte := Byte and not (Shift_Left (1, Y mod 8)); else Byte := Byte or Shift_Left (1, Y mod 8); end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point; Color : Bitmap_Color) is begin Buffer.Set_Pixel (Pt, (if Color = Black then 0 else 1)); end Set_Pixel; --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point; Raw : UInt32) is begin Buffer.Native_Source := Raw; Buffer.Set_Pixel (Pt); end Set_Pixel; ----------- -- Pixel -- ----------- overriding function Pixel (Buffer : SSD1306_Bitmap_Buffer; Pt : Point) return Bitmap_Color is begin return (if Buffer.Pixel (Pt) = 0 then Black else White); end Pixel; ----------- -- Pixel -- ----------- overriding function Pixel (Buffer : SSD1306_Bitmap_Buffer; Pt : Point) return UInt32 is X : constant Natural := Buffer.Width - 1 - Pt.X; Y : constant Natural := Buffer.Height - 1 - Pt.Y; Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width; Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index); begin if (Byte and (Shift_Left (1, Y mod 8))) /= 0 then return 1; else return 0; end if; end Pixel; ---------- -- Fill -- ---------- overriding procedure Fill (Buffer : in out SSD1306_Bitmap_Buffer) is Val : constant UInt8 := (if Buffer.Native_Source /= 0 then 16#FF# else 0); begin Buffer.Data := (others => Val); end Fill; end SSD1306;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package body SSD1306 is procedure Write_Command (This : SSD1306_Screen; Cmd : UInt8); procedure Write_Data (This : SSD1306_Screen; Data : UInt8_Array); ------------------- -- Write_Command -- ------------------- procedure Write_Command (This : SSD1306_Screen; Cmd : UInt8) is Status : I2C_Status; begin This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr, Data => (1 => 0, 2 => (Cmd)), Status => Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; end Write_Command; ---------------- -- Write_Data -- ---------------- procedure Write_Data (This : SSD1306_Screen; Data : UInt8_Array) is Status : I2C_Status; begin This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr, Data => Data, Status => Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; end Write_Data; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out SSD1306_Screen; External_VCC : Boolean) is begin if This.Width * This.Height /= (This.Buffer_Size_In_Byte * 8) then raise Program_Error with "Invalid screen parameters"; end if; This.RST.Clear; This.Time.Delay_Milliseconds (100); This.RST.Set; This.Time.Delay_Milliseconds (100); Write_Command (This, DISPLAY_OFF); Write_Command (This, SET_DISPLAY_CLOCK_DIV); Write_Command (This, 16#80#); Write_Command (This, SET_MULTIPLEX); Write_Command (This, UInt8 (This.Height - 1)); Write_Command (This, SET_DISPLAY_OFFSET); Write_Command (This, 16#00#); Write_Command (This, SET_START_LINE or 0); Write_Command (This, CHARGE_PUMP); Write_Command (This, (if External_VCC then 16#10# else 16#14#)); Write_Command (This, MEMORY_MODE); Write_Command (This, 16#00#); Write_Command (This, SEGREMAP or 1); Write_Command (This, COM_SCAN_DEC); Write_Command (This, SET_COMPINS); if This.Height > 32 then Write_Command (This, 16#12#); else Write_Command (This, 16#02#); end if; Write_Command (This, SET_CONTRAST); Write_Command (This, 16#AF#); Write_Command (This, SET_PRECHARGE); Write_Command (This, (if External_VCC then 16#22# else 16#F1#)); Write_Command (This, SET_VCOM_DETECT); Write_Command (This, 16#40#); Write_Command (This, DISPLAY_ALL_ON_RESUME); Write_Command (This, NORMAL_DISPLAY); Write_Command (This, DEACTIVATE_SCROLL); This.Device_Initialized := True; end Initialize; ----------------- -- Initialized -- ----------------- overriding function Initialized (This : SSD1306_Screen) return Boolean is (This.Device_Initialized); ------------- -- Turn_On -- ------------- procedure Turn_On (This : SSD1306_Screen) is begin Write_Command (This, DISPLAY_ON); end Turn_On; -------------- -- Turn_Off -- -------------- procedure Turn_Off (This : SSD1306_Screen) is begin Write_Command (This, DISPLAY_OFF); end Turn_Off; -------------------------- -- Display_Inversion_On -- -------------------------- procedure Display_Inversion_On (This : SSD1306_Screen) is begin Write_Command (This, INVERT_DISPLAY); end Display_Inversion_On; --------------------------- -- Display_Inversion_Off -- --------------------------- procedure Display_Inversion_Off (This : SSD1306_Screen) is begin Write_Command (This, NORMAL_DISPLAY); end Display_Inversion_Off; ---------------------- -- Write_Raw_Pixels -- ---------------------- procedure Write_Raw_Pixels (This : SSD1306_Screen; Data : HAL.UInt8_Array) is begin Write_Command (This, COLUMN_ADDR); Write_Command (This, 0); -- from Write_Command (This, UInt8 (This.Width - 1)); -- to Write_Command (This, PAGE_ADDR); Write_Command (This, 0); -- from Write_Command (This, UInt8 (This.Height / 8) - 1); -- to Write_Data (This, (1 => 16#40#) & Data); end Write_Raw_Pixels; -------------------- -- Get_Max_Layers -- -------------------- overriding function Max_Layers (This : SSD1306_Screen) return Positive is (1); ------------------ -- Is_Supported -- ------------------ overriding function Supported (This : SSD1306_Screen; Mode : FB_Color_Mode) return Boolean is (Mode = HAL.Bitmap.RGB_565); --------------------- -- Set_Orientation -- --------------------- overriding procedure Set_Orientation (This : in out SSD1306_Screen; Orientation : Display_Orientation) is begin null; end Set_Orientation; -------------- -- Set_Mode -- -------------- overriding procedure Set_Mode (This : in out SSD1306_Screen; Mode : Wait_Mode) is begin null; end Set_Mode; --------------- -- Get_Width -- --------------- overriding function Width (This : SSD1306_Screen) return Positive is (This.Width); ---------------- -- Get_Height -- ---------------- overriding function Height (This : SSD1306_Screen) return Positive is (This.Height); ---------------- -- Is_Swapped -- ---------------- overriding function Swapped (This : SSD1306_Screen) return Boolean is (False); -------------------- -- Set_Background -- -------------------- overriding procedure Set_Background (This : SSD1306_Screen; R, G, B : UInt8) is begin -- Does it make sense when there's no alpha channel... raise Program_Error; end Set_Background; ---------------------- -- Initialize_Layer -- ---------------------- overriding procedure Initialize_Layer (This : in out SSD1306_Screen; Layer : Positive; Mode : FB_Color_Mode; X : Natural := 0; Y : Natural := 0; Width : Positive := Positive'Last; Height : Positive := Positive'Last) is pragma Unreferenced (X, Y, Width, Height); begin if Layer /= 1 or else Mode /= M_1 then raise Program_Error; end if; This.Memory_Layer.Actual_Width := This.Width; This.Memory_Layer.Actual_Height := This.Height; This.Memory_Layer.Addr := This.Memory_Layer.Data'Address; This.Memory_Layer.Actual_Color_Mode := Mode; This.Layer_Initialized := True; end Initialize_Layer; ----------------- -- Initialized -- ----------------- overriding function Initialized (This : SSD1306_Screen; Layer : Positive) return Boolean is begin return Layer = 1 and then This.Layer_Initialized; end Initialized; ------------------ -- Update_Layer -- ------------------ overriding procedure Update_Layer (This : in out SSD1306_Screen; Layer : Positive; Copy_Back : Boolean := False) is pragma Unreferenced (Copy_Back); begin if Layer /= 1 then raise Program_Error; end if; This.Write_Raw_Pixels (This.Memory_Layer.Data); end Update_Layer; ------------------- -- Update_Layers -- ------------------- overriding procedure Update_Layers (This : in out SSD1306_Screen) is begin This.Update_Layer (1); end Update_Layers; -------------------- -- Get_Color_Mode -- -------------------- overriding function Color_Mode (This : SSD1306_Screen; Layer : Positive) return FB_Color_Mode is pragma Unreferenced (This); begin if Layer /= 1 then raise Program_Error; end if; return M_1; end Color_Mode; ----------------------- -- Get_Hidden_Buffer -- ----------------------- overriding function Hidden_Buffer (This : in out SSD1306_Screen; Layer : Positive) return not null HAL.Bitmap.Any_Bitmap_Buffer is begin if Layer /= 1 then raise Program_Error; end if; return This.Memory_Layer'Unchecked_Access; end Hidden_Buffer; -------------------- -- Get_Pixel_Size -- -------------------- overriding function Pixel_Size (This : SSD1306_Screen; Layer : Positive) return Positive is (1); --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point) is X : constant Natural := Buffer.Width - 1 - Pt.X; Y : constant Natural := Buffer.Height - 1 - Pt.Y; Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width; Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index); begin if Buffer.Native_Source = 0 then Byte := Byte and not (Shift_Left (1, Y mod 8)); else Byte := Byte or Shift_Left (1, Y mod 8); end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point; Color : Bitmap_Color) is begin Buffer.Set_Pixel (Pt, (if Color = Black then 0 else 1)); end Set_Pixel; --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : in out SSD1306_Bitmap_Buffer; Pt : Point; Raw : UInt32) is begin Buffer.Native_Source := Raw; Buffer.Set_Pixel (Pt); end Set_Pixel; ----------- -- Pixel -- ----------- overriding function Pixel (Buffer : SSD1306_Bitmap_Buffer; Pt : Point) return Bitmap_Color is begin return (if Buffer.Pixel (Pt) = 0 then Black else White); end Pixel; ----------- -- Pixel -- ----------- overriding function Pixel (Buffer : SSD1306_Bitmap_Buffer; Pt : Point) return UInt32 is X : constant Natural := Buffer.Width - 1 - Pt.X; Y : constant Natural := Buffer.Height - 1 - Pt.Y; Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width; Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index); begin if (Byte and (Shift_Left (1, Y mod 8))) /= 0 then return 1; else return 0; end if; end Pixel; ---------- -- Fill -- ---------- overriding procedure Fill (Buffer : in out SSD1306_Bitmap_Buffer) is Val : constant UInt8 := (if Buffer.Native_Source /= 0 then 16#FF# else 0); begin Buffer.Data := (others => Val); end Fill; end SSD1306;
Fix initialization for 128x64 displays
SSD1306: Fix initialization for 128x64 displays
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
4a14d089d74fd831c6845f88a5be77736ca5e9dc
asfunit/asf-tests.ads
asfunit/asf-tests.ads
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
Declare the Assert_Header procedure to check that the response contains the expected header
Declare the Assert_Header procedure to check that the response contains the expected header
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
5fc1d3863211037022777dbcb7dbffcdf0d57b69
awt/example/src/example.adb
awt/example/src/example.adb
with Ada.Exceptions; with Ada.Real_Time; with Ada.Text_IO; with AWT.Clipboard; with AWT.Drag_And_Drop; with AWT.Inputs; with AWT.Monitors; with AWT.Windows; with Orka.Contexts.AWT; with Orka.Debug; with Package_Test; procedure Example is use Ada.Text_IO; Index : Positive := 1; Monitor_Events, Last_Monitor_Events : Positive := 1; Border_Size : constant := 50; Should_Be_Visible : Boolean := True; Visible_Index : Positive := 1; Visible_Index_Count : constant := 100; procedure Print_Monitor (Monitor : AWT.Monitors.Monitor_Ptr) is State : constant AWT.Monitors.Monitor_State := Monitor.State; use AWT.Monitors; begin Put_Line ("monitor:" & Monitor.ID'Image); Put_Line (" name: " & (+State.Name)); Put_Line (" x, y: " & State.X'Image & ", " & State.Y'Image); Put_Line (" w x h: " & State.Width'Image & " × " & State.Height'Image); Put_Line (" refresh: " & State.Refresh'Image); end Print_Monitor; type Test_Listener is new AWT.Monitors.Monitor_Event_Listener with null record; overriding procedure On_Connect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr); overriding procedure On_Disconnect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr); overriding procedure On_Connect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr) is begin Put_Line ("connected:"); Print_Monitor (Monitor); Monitor_Events := Monitor_Events + 1; end On_Connect; overriding procedure On_Disconnect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr) is begin Put_Line ("disconnected:"); Print_Monitor (Monitor); Monitor_Events := Monitor_Events + 1; end On_Disconnect; Monitor_Listener : Test_Listener; begin Put_Line ("Initializing..."); AWT.Initialize; Put_Line ("Initialized"); for Monitor of AWT.Monitors.Monitors loop Print_Monitor (Monitor); end loop; declare Next_Cursor : AWT.Inputs.Cursors.Pointer_Cursor := AWT.Inputs.Cursors.Pointer_Cursor'First; Last_Pointer : AWT.Inputs.Pointer_State; Last_Keyboard : AWT.Inputs.Keyboard_State; use Ada.Real_Time; Interval : constant Duration := To_Duration (Microseconds (16_667)); Flip_Size : Boolean := False; Context : constant Orka.Contexts.Surface_Context'Class := Orka.Contexts.AWT.Create_Context (Version => (4, 2), Flags => (Debug | Robust => True, others => False)); Window : Package_Test.Test_Window := Package_Test.Create_Window (Context, 600, 400, Visible => True, Transparent => True, Title => "init test"); AWT_Window : AWT.Windows.Window'Class renames AWT.Windows.Window'Class (Window); task Render_Task is entry Start_Rendering; end Render_Task; task body Render_Task is begin Put_Line ("Render task waiting to get started..."); accept Start_Rendering; Put_Line ("Render task started"); Context.Make_Current (Window); Put_Line ("Window made current on context"); Orka.Debug.Set_Log_Messages (Enable => True); Put_Line ("Context version: " & Orka.Contexts.Image (Context.Version)); Window.Post_Initialize; Put_Line ("Rendering..."); loop exit when Window.Should_Close; delay until Clock + Microseconds (15000); Window.Render; end loop; Put_Line ("Rendering done"); Context.Make_Not_Current; Put_Line ("Render task, context made not current"); exception when E : others => Put_Line (Ada.Exceptions.Exception_Information (E)); Context.Make_Not_Current; raise; end Render_Task; begin Last_Pointer := AWT_Window.State; Last_Keyboard := AWT_Window.State; Context.Make_Not_Current; Put_Line ("Context made not current in main task"); Render_Task.Start_Rendering; Put_Line ("Render task started by main task"); Window.Set_Margin (Border_Size); Put_Line ("Starting event loop..."); while not Window.Should_Close and then AWT.Process_Events (Interval) loop -- AWT_Window.Set_Title (Index'Image & " " & Next_Cursor'Image); Index := Index + 1; select Package_Test.Dnd_Signal.Wait; declare Result : constant String := AWT.Drag_And_Drop.Get; begin Put_Line ("value: '" & Result & "'"); AWT.Drag_And_Drop.Finish (AWT.Inputs.Copy); end; else null; end select; if not Should_Be_Visible then Put_Line (Positive'Image (Visible_Index + Visible_Index_Count) & Index'Image); if Index > Visible_Index + Visible_Index_Count then Should_Be_Visible := True; AWT_Window.Set_Title ("visible! " & Visible_Index'Image); AWT_Window.Set_Visible (True); Put_Line ("window visible"); end if; end if; -- if Index = 100 then -- AWT_Window.Set_Visible (True); -- end if; if Monitor_Events /= Last_Monitor_Events then Put_Line ("Monitor count: " & Natural'Image (AWT.Monitors.Monitors'Length)); Last_Monitor_Events := Monitor_Events; end if; declare Pointer : constant AWT.Inputs.Pointer_State := AWT_Window.State; use all type AWT.Inputs.Button_State; use all type AWT.Inputs.Dimension; use all type AWT.Inputs.Pointer_Button; use all type AWT.Inputs.Pointer_Mode; use type AWT.Inputs.Cursors.Pointer_Cursor; begin -- if False then -- Put_Line ("focused: " & Pointer.Focused'Image); -- Put_Line ("scrolling: " & Pointer.Scrolling'Image); -- Put_Line ("buttons:"); -- Put_Line (" left: " & Pointer.Buttons (Left)'Image); -- Put_Line (" middle: " & Pointer.Buttons (Middle)'Image); -- Put_Line (" right: " & Pointer.Buttons (Right)'Image); -- Put_Line ("mode: " & Pointer.Mode'Image); -- Put_Line ("position: " & Pointer.Position (X)'Image & Pointer.Position (Y)'Image); -- Put_Line ("relative: " & Pointer.Relative (X)'Image & Pointer.Relative (Y)'Image); -- Put_Line ("scroll: " & Pointer.Scroll (X)'Image & Pointer.Scroll (Y)'Image); -- end if; -- if Last_Pointer.Focused and not Pointer.Focused then -- Window.Set_Pointer_Cursor (AWT.Inputs.Cursors.Pointer_Cursor'Last); -- end if; if Pointer.Buttons (Left) = Pressed and Last_Pointer.Buttons (Left) = Released then Next_Cursor := (if Next_Cursor = AWT.Inputs.Cursors.Pointer_Cursor'Last then AWT.Inputs.Cursors.Pointer_Cursor'First else AWT.Inputs.Cursors.Pointer_Cursor'Succ (Next_Cursor)); AWT_Window.Set_Pointer_Cursor (Next_Cursor); end if; if Pointer.Buttons (Right) = Pressed and Last_Pointer.Buttons (Right) = Released and Pointer.Mode /= Locked then Put_Line ("locking!"); AWT_Window.Set_Pointer_Mode (Locked); elsif Pointer.Buttons (Right) = Released and Last_Pointer.Buttons (Right) = Pressed and Pointer.Mode = Locked then Put_Line ("unlocking!"); AWT_Window.Set_Pointer_Mode (Visible); end if; Last_Pointer := Pointer; end; declare Keyboard : constant AWT.Inputs.Keyboard_State := AWT_Window.State; use type AWT.Inputs.Keyboard_Modifiers; use all type AWT.Inputs.Button_State; use all type AWT.Inputs.Keyboard_Button; begin if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_C) = Pressed and Keyboard.Buttons (Key_C) = Released then declare Value : constant String := "foobar" & Index'Image; begin AWT.Clipboard.Set (Value); Put_Line ("Set clipboard: '" & Value & "'"); end; end if; if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_V) = Pressed and Keyboard.Buttons (Key_V) = Released then Put_Line ("Get clipboard: '" & AWT.Clipboard.Get & "'"); end if; -- Put_Line ("focused: " & Keyboard.Focused'Image); -- Put_Line ("repeat:"); -- Put_Line (" rate: " & Keyboard.Repeat_Rate'Image); -- Put_Line (" delay: " & Keyboard.Repeat_Delay'Image); -- if False and Keyboard.Modifiers /= Last_Keyboard.Modifiers then -- Put_Line ("Shift: " & Keyboard.Modifiers.Shift'Image); -- Put_Line ("Caps_Lock: " & Keyboard.Modifiers.Caps_Lock'Image); -- Put_Line ("Ctrl: " & Keyboard.Modifiers.Ctrl'Image); -- Put_Line ("Alt: " & Keyboard.Modifiers.Alt'Image); -- Put_Line ("Num_Lock: " & Keyboard.Modifiers.Num_Lock'Image); -- Put_Line ("Logo: " & Keyboard.Modifiers.Logo'Image); -- end if; declare use all type AWT.Windows.Size_Mode; begin if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_F) = Pressed and Keyboard.Buttons (Key_F) = Released then if AWT_Window.State.Mode = Fullscreen then AWT_Window.Set_Size_Mode (Default); else AWT_Window.Set_Size_Mode (Fullscreen); end if; end if; if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_M) = Pressed and Keyboard.Buttons (Key_M) = Released then if AWT_Window.State.Mode = Maximized then AWT_Window.Set_Size_Mode (Default); else AWT_Window.Set_Size_Mode (Maximized); end if; end if; if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_S) = Pressed and Keyboard.Buttons (Key_S) = Released then Flip_Size := not Flip_Size; if Flip_Size then AWT_Window.Set_Size (1280, 720); else AWT_Window.Set_Size (600, 400); end if; end if; if Keyboard.Modifiers.Ctrl and Last_Keyboard.Buttons (Key_H) = Pressed and Keyboard.Buttons (Key_H) = Released then Should_Be_Visible := False; Visible_Index := Index; AWT_Window.Set_Visible (False); Put_Line ("window hidden"); end if; end; Last_Keyboard := Keyboard; end; end loop; Put_Line ("Exited event loop"); exception when E : others => Put_Line ("main: " & Ada.Exceptions.Exception_Information (E)); raise; end; end Example;
with Ada.Exceptions; with Ada.Real_Time; with Ada.Text_IO; with AWT.Clipboard; with AWT.Drag_And_Drop; with AWT.Inputs; with AWT.Monitors; with AWT.Windows; with Orka.Contexts.AWT; with Orka.Debug; with Package_Test; procedure Example is use Ada.Text_IO; Index : Positive := 1; Monitor_Events, Last_Monitor_Events : Positive := 1; Border_Size : constant := 50; Should_Be_Visible : Boolean := True; Visible_Index : Positive := 1; Visible_Index_Count : constant := 100; procedure Print_Monitor (Monitor : AWT.Monitors.Monitor_Ptr) is State : constant AWT.Monitors.Monitor_State := Monitor.State; use AWT.Monitors; begin Put_Line ("monitor:" & Monitor.ID'Image); Put_Line (" name: " & (+State.Name)); Put_Line (" x, y: " & State.X'Image & ", " & State.Y'Image); Put_Line (" w x h: " & State.Width'Image & " × " & State.Height'Image); Put_Line (" refresh: " & State.Refresh'Image); end Print_Monitor; type Test_Listener is new AWT.Monitors.Monitor_Event_Listener with null record; overriding procedure On_Connect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr); overriding procedure On_Disconnect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr); overriding procedure On_Connect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr) is begin Put_Line ("connected:"); Print_Monitor (Monitor); Monitor_Events := Monitor_Events + 1; end On_Connect; overriding procedure On_Disconnect (Object : Test_Listener; Monitor : AWT.Monitors.Monitor_Ptr) is begin Put_Line ("disconnected:"); Print_Monitor (Monitor); Monitor_Events := Monitor_Events + 1; end On_Disconnect; Monitor_Listener : Test_Listener; begin Put_Line ("Initializing..."); AWT.Initialize; Put_Line ("Initialized"); for Monitor of AWT.Monitors.Monitors loop Print_Monitor (Monitor); end loop; declare Next_Cursor : AWT.Inputs.Cursors.Pointer_Cursor := AWT.Inputs.Cursors.Pointer_Cursor'First; Last_Pointer : AWT.Inputs.Pointer_State; use Ada.Real_Time; Interval : constant Duration := To_Duration (Microseconds (16_667)); Flip_Size : Boolean := False; Context : constant Orka.Contexts.Surface_Context'Class := Orka.Contexts.AWT.Create_Context (Version => (4, 2), Flags => (Debug | Robust => True, others => False)); Window : Package_Test.Test_Window := Package_Test.Create_Window (Context, 600, 400, Visible => True, Transparent => True, Title => "init test"); AWT_Window : AWT.Windows.Window'Class renames AWT.Windows.Window'Class (Window); task Render_Task is entry Start_Rendering; end Render_Task; task body Render_Task is begin Put_Line ("Render task waiting to get started..."); accept Start_Rendering; Put_Line ("Render task started"); Context.Make_Current (Window); Put_Line ("Window made current on context"); Orka.Debug.Set_Log_Messages (Enable => True); Put_Line ("Context version: " & Orka.Contexts.Image (Context.Version)); Window.Post_Initialize; Put_Line ("Rendering..."); loop exit when Window.Should_Close; delay until Clock + Microseconds (15000); Window.Render; end loop; Put_Line ("Rendering done"); Context.Make_Not_Current; Put_Line ("Render task, context made not current"); exception when E : others => Put_Line (Ada.Exceptions.Exception_Information (E)); Context.Make_Not_Current; raise; end Render_Task; begin Last_Pointer := AWT_Window.State; Context.Make_Not_Current; Put_Line ("Context made not current in main task"); Render_Task.Start_Rendering; Put_Line ("Render task started by main task"); Window.Set_Margin (Border_Size); Put_Line ("Starting event loop..."); while not Window.Should_Close loop AWT.Process_Events (Interval); -- AWT_Window.Set_Title (Index'Image & " " & Next_Cursor'Image); Index := Index + 1; select Package_Test.Dnd_Signal.Wait; declare Result : constant String := AWT.Drag_And_Drop.Get; begin Put_Line ("value: '" & Result & "'"); AWT.Drag_And_Drop.Finish (AWT.Inputs.Copy); end; else null; end select; if not Should_Be_Visible then Put_Line (Positive'Image (Visible_Index + Visible_Index_Count) & Index'Image); if Index > Visible_Index + Visible_Index_Count then Should_Be_Visible := True; AWT_Window.Set_Title ("visible! " & Visible_Index'Image); AWT_Window.Set_Visible (True); Put_Line ("window visible"); end if; end if; -- if Index = 100 then -- AWT_Window.Set_Visible (True); -- end if; if Monitor_Events /= Last_Monitor_Events then Put_Line ("Monitor count: " & Natural'Image (AWT.Monitors.Monitors'Length)); Last_Monitor_Events := Monitor_Events; end if; declare Pointer : constant AWT.Inputs.Pointer_State := AWT_Window.State; use all type AWT.Inputs.Button_State; use all type AWT.Inputs.Dimension; use all type AWT.Inputs.Pointer_Button; use all type AWT.Inputs.Pointer_Mode; use type AWT.Inputs.Cursors.Pointer_Cursor; begin -- if False then -- Put_Line ("focused: " & Pointer.Focused'Image); -- Put_Line ("scrolling: " & Pointer.Scrolling'Image); -- Put_Line ("buttons:"); -- Put_Line (" left: " & Pointer.Buttons (Left)'Image); -- Put_Line (" middle: " & Pointer.Buttons (Middle)'Image); -- Put_Line (" right: " & Pointer.Buttons (Right)'Image); -- Put_Line ("mode: " & Pointer.Mode'Image); -- Put_Line ("position: " & Pointer.Position (X)'Image & Pointer.Position (Y)'Image); -- Put_Line ("relative: " & Pointer.Relative (X)'Image & Pointer.Relative (Y)'Image); -- Put_Line ("scroll: " & Pointer.Scroll (X)'Image & Pointer.Scroll (Y)'Image); -- end if; -- if Last_Pointer.Focused and not Pointer.Focused then -- Window.Set_Pointer_Cursor (AWT.Inputs.Cursors.Pointer_Cursor'Last); -- end if; if Pointer.Buttons (Left) = Pressed and Last_Pointer.Buttons (Left) = Released then Next_Cursor := (if Next_Cursor = AWT.Inputs.Cursors.Pointer_Cursor'Last then AWT.Inputs.Cursors.Pointer_Cursor'First else AWT.Inputs.Cursors.Pointer_Cursor'Succ (Next_Cursor)); AWT_Window.Set_Pointer_Cursor (Next_Cursor); end if; if Pointer.Buttons (Right) = Pressed and Last_Pointer.Buttons (Right) = Released and Pointer.Mode /= Locked then Put_Line ("locking!"); AWT_Window.Set_Pointer_Mode (Locked); elsif Pointer.Buttons (Right) = Released and Last_Pointer.Buttons (Right) = Pressed and Pointer.Mode = Locked then Put_Line ("unlocking!"); AWT_Window.Set_Pointer_Mode (Visible); end if; Last_Pointer := Pointer; end; declare Keyboard : constant AWT.Inputs.Keyboard_State := AWT_Window.State; use type AWT.Inputs.Keyboard_Modifiers; use all type AWT.Inputs.Button_State; use all type AWT.Inputs.Keyboard_Button; begin if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_C) then declare Value : constant String := "foobar" & Index'Image; begin AWT.Clipboard.Set (Value); Put_Line ("Set clipboard: '" & Value & "'"); end; end if; if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_V) then Put_Line ("Get clipboard: '" & AWT.Clipboard.Get & "'"); end if; -- Put_Line ("focused: " & Keyboard.Focused'Image); -- Put_Line ("repeat:"); -- Put_Line (" rate: " & Keyboard.Repeat_Rate'Image); -- Put_Line (" delay: " & Keyboard.Repeat_Delay'Image); -- if False and Keyboard.Modifiers /= Last_Keyboard.Modifiers then -- Put_Line ("Shift: " & Keyboard.Modifiers.Shift'Image); -- Put_Line ("Caps_Lock: " & Keyboard.Modifiers.Caps_Lock'Image); -- Put_Line ("Ctrl: " & Keyboard.Modifiers.Ctrl'Image); -- Put_Line ("Alt: " & Keyboard.Modifiers.Alt'Image); -- Put_Line ("Num_Lock: " & Keyboard.Modifiers.Num_Lock'Image); -- Put_Line ("Logo: " & Keyboard.Modifiers.Logo'Image); -- end if; declare use all type AWT.Windows.Size_Mode; begin if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_F) then if AWT_Window.State.Mode = Fullscreen then AWT_Window.Set_Size_Mode (Default); else AWT_Window.Set_Size_Mode (Fullscreen); end if; end if; if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_M) then if AWT_Window.State.Mode = Maximized then AWT_Window.Set_Size_Mode (Default); else AWT_Window.Set_Size_Mode (Maximized); end if; end if; if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_S) then Flip_Size := not Flip_Size; if Flip_Size then AWT_Window.Set_Size (1280, 720); else AWT_Window.Set_Size (600, 400); end if; end if; if Keyboard.Modifiers.Ctrl and Keyboard.Pressed (Key_H) then Should_Be_Visible := False; Visible_Index := Index; AWT_Window.Set_Visible (False); Put_Line ("window hidden"); end if; end; end; end loop; Put_Line ("Exited event loop"); exception when E : others => Put_Line ("main: " & Ada.Exceptions.Exception_Information (E)); raise; end; end Example;
Fix and clean up example code after changing AWT.Process_Events
awt: Fix and clean up example code after changing AWT.Process_Events Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
670ef5db4d66fcef96d69065965e85ede5c29bde
mat/src/mat-readers-streams-files.adb
mat/src/mat-readers-streams-files.adb
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014, 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.Streams.Stream_IO; with Util.Log.Loggers; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Open the file. -- ------------------------------ procedure Open (Reader : in out File_Reader_Type; Path : in String) is Stream : constant access Util.Streams.Input_Stream'Class := Reader.File'Access; begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Stream); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014, 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.Streams.Stream_IO; with Util.Log.Loggers; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Open the file. -- ------------------------------ procedure Open (Reader : in out File_Reader_Type; Path : in String) is Stream : constant access Util.Streams.Input_Stream'Class := Reader.File'Unchecked_Access; begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Stream); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
779aa9cc1d1ac5a28b2ad89091dd0dc558e22776
src/ado-drivers-dialects.ads
src/ado-drivers-dialects.ads
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects. package ADO.Drivers.Dialects is -- -------------------- -- SQL Dialect -- -------------------- -- The <b>Dialect</b> defines the specific characteristics that must be -- taken into account when building the SQL statement. This includes: -- <ul> -- <li>The definition of reserved keywords that must be escaped</li> -- <li>How to escape those keywords</li> -- <li>How to escape special characters</li> -- </ul> type Dialect is abstract tagged private; type Dialect_Access is access all Dialect'Class; -- Check if the string is a reserved keyword. function Is_Reserved (D : Dialect; Name : String) return Boolean is abstract; -- Get the quote character to escape an identifier. function Get_Identifier_Quote (D : in Dialect) return Character is abstract; -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String); -- Append the item in the buffer escaping some characters if necessary procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in ADO.Blob_Ref); -- Append the boolean item in the buffer. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean); private type Dialect is abstract tagged null record; end ADO.Drivers.Dialects;
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects. package ADO.Drivers.Dialects is -- -------------------- -- SQL Dialect -- -------------------- -- The <b>Dialect</b> defines the specific characteristics that must be -- taken into account when building the SQL statement. This includes: -- <ul> -- <li>The definition of reserved keywords that must be escaped</li> -- <li>How to escape those keywords</li> -- <li>How to escape special characters</li> -- </ul> type Dialect is abstract tagged private; type Dialect_Access is access all Dialect'Class; -- Check if the string is a reserved keyword. function Is_Reserved (D : Dialect; Name : String) return Boolean is abstract; -- Get the quote character to escape an identifier. function Get_Identifier_Quote (D : in Dialect) return Character is abstract; -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String); -- Append the item in the buffer escaping some characters if necessary procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in ADO.Blob_Ref) is abstract; -- Append the boolean item in the buffer. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean); private type Dialect is abstract tagged null record; end ADO.Drivers.Dialects;
Make Escape_Sql procedure abstract
Make Escape_Sql procedure abstract
Ada
apache-2.0
stcarrez/ada-ado
8a276ab713381df2017f780b010d4afd963bbd11
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unchecked_Access; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; return R; end Get_Master_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
Remove Open_Session procedure which is not used
Remove Open_Session procedure which is not used
Ada
apache-2.0
stcarrez/ada-ado
fd6ada01d2d5081f7fc656f1955e3285a8c11c0a
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-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; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-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; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Fix XML generation if a message contains < or >
Fix XML generation if a message contains < or >
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cc303f26966a9426f77d73a5a142216381840571
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Attributes is -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_UString (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Wiki.Strings.Null_UString; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Wiki.Strings.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString) is begin Append (List, Wiki.Strings.To_WString (Name), Wiki.Strings.To_WString (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString) is Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Attributes is -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_UString (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Wiki.Strings.Null_UString; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Wiki.Strings.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Name, Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString) is begin Append (List, Wiki.Strings.To_WString (Name), Wiki.Strings.To_WString (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString) is Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
Implement Append procedure with WString value
Implement Append procedure with WString value
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
665c931f6b528df015015701cabcd830003521a8
src/dynamo.adb
src/dynamo.adb
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Traceback.Symbolic; with Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Directories; with Ada.Command_Line; with Util.Files; with Util.Log.Loggers; with Gen.Generator; with Gen.Commands; with Gen.Configs; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Directories; use Ada.Command_Line; use Gen.Commands; procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False); procedure Print_Configuration (Generator : in Gen.Generator.Handler); Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; Status : Exit_Status := Success; Debug : Boolean := False; Print_Config : Boolean := False; -- ------------------------------ -- Print information about dynamo configuration -- ------------------------------ procedure Print_Configuration (Generator : in Gen.Generator.Handler) is begin Ada.Text_IO.Put_Line ("Dynamo version : " & Gen.Configs.VERSION); Ada.Text_IO.Put_Line ("Config directory : " & Generator.Get_Config_Directory); Ada.Text_IO.Put_Line ("UML directory : " & Generator.Get_Parameter (Gen.Configs.GEN_UML_DIR)); Ada.Text_IO.Put_Line ("Templates directory : " & Generator.Get_Parameter (Gen.Configs.GEN_TEMPLATES_DIRS)); Ada.Text_IO.Put_Line ("GNAT project directory : " & Generator.Get_Parameter (Gen.Configs.GEN_GNAT_PROJECT_DIRS)); end Print_Configuration; -- ------------------------------ -- Verify and set the configuration path -- ------------------------------ procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False) is Log_Path : constant String := Ada.Directories.Compose (Path, "log4j.properties"); begin -- Ignore if the config directory was already set. if Length (Config_Dir) > 0 then return; end if; -- Check that we can read some configuration file. if not Ada.Directories.Exists (Log_Path) then if not Silent then Ada.Text_IO.Put_Line ("Invalid config directory: " & Path); Status := Failure; end if; return; end if; -- Configure the logs Util.Log.Loggers.Initialize (Log_Path); Config_Dir := To_Unbounded_String (Path); end Set_Config_Directory; begin Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d o: t: c:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Set_Config_Directory (Parameter); when 'd' => Debug := True; when 'v' => Print_Config := True; when '*' => exit; when others => null; end case; end loop; if Length (Config_Dir) = 0 then declare Name : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Name); Dir : constant String := Containing_Directory (Path); begin Set_Config_Directory (Compose (Dir, "config"), True); Set_Config_Directory (Util.Files.Compose (Dir, "share/dynamo/base"), True); Set_Config_Directory (Gen.Configs.CONFIG_DIR, True); end; end if; if Status /= Success then Gen.Commands.Short_Help_Usage; Ada.Command_Line.Set_Exit_Status (Status); return; end if; if Ada.Command_Line.Argument_Count = 0 then Gen.Commands.Short_Help_Usage; Set_Exit_Status (Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Cmd : Gen.Commands.Command_Access; Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, To_String (Out_Dir)); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir, Debug); if Print_Config then Print_Configuration (Generator); return; end if; Cmd := Gen.Commands.Find_Command (Cmd_Name); -- Check that the command exists. if Cmd = null then if Cmd_Name'Length > 0 then Ada.Text_IO.Put_Line ("Invalid command: '" & Cmd_Name & "'"); end if; Gen.Commands.Short_Help_Usage; Set_Exit_Status (Failure); return; end if; Cmd.Execute (Generator); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Gen.Commands.Short_Help_Usage; Ada.Command_Line.Set_Exit_Status (2); when E : Gen.Generator.Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : Sax.Readers.XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end Dynamo;
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Traceback.Symbolic; with Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Directories; with Ada.Command_Line; with Ada.Environment_Variables; with Util.Files; with Util.Log.Loggers; with Gen.Utils.GNAT; with Gen.Generator; with Gen.Commands; with Gen.Configs; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Directories; use Ada.Command_Line; use Gen.Commands; procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False); procedure Print_Configuration (Generator : in Gen.Generator.Handler); -- Print environment variable setup procedure Print_Environment (Generator : in Gen.Generator.Handler; C_Env : in Boolean := False); Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; Status : Exit_Status := Success; Debug : Boolean := False; Print_Config : Boolean := False; Print_Env : Boolean := False; Print_CEnv : Boolean := False; -- ------------------------------ -- Print information about dynamo configuration -- ------------------------------ procedure Print_Configuration (Generator : in Gen.Generator.Handler) is begin Ada.Text_IO.Put_Line ("Dynamo version : " & Gen.Configs.VERSION); Ada.Text_IO.Put_Line ("Config directory : " & Generator.Get_Config_Directory); Ada.Text_IO.Put_Line ("UML directory : " & Generator.Get_Parameter (Gen.Configs.GEN_UML_DIR)); Ada.Text_IO.Put_Line ("Templates directory : " & Generator.Get_Parameter (Gen.Configs.GEN_TEMPLATES_DIRS)); Ada.Text_IO.Put_Line ("GNAT project directory : " & Generator.Get_Parameter (Gen.Configs.GEN_GNAT_PROJECT_DIRS)); end Print_Configuration; -- ------------------------------ -- Print environment variable setup -- ------------------------------ procedure Print_Environment (Generator : in Gen.Generator.Handler; C_Env : in Boolean := False) is begin if C_Env then Ada.Text_IO.Put ("setenv " & Gen.Utils.GNAT.ADA_PROJECT_PATH_NAME & " """); else Ada.Text_IO.Put ("export " & Gen.Utils.GNAT.ADA_PROJECT_PATH_NAME & "="""); end if; if Ada.Environment_Variables.Exists (Gen.Utils.GNAT.ADA_PROJECT_PATH_NAME) then Ada.Text_IO.Put (Ada.Environment_Variables.Value (Gen.Utils.GNAT.ADA_PROJECT_PATH_NAME)); -- Ada.Text_IO.Put ( end if; Ada.Text_IO.Put_Line (Generator.Get_Parameter (Gen.Configs.GEN_GNAT_PROJECT_DIRS) & """"); end Print_Environment; -- ------------------------------ -- Verify and set the configuration path -- ------------------------------ procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False) is Log_Path : constant String := Ada.Directories.Compose (Path, "log4j.properties"); begin -- Ignore if the config directory was already set. if Length (Config_Dir) > 0 then return; end if; -- Check that we can read some configuration file. if not Ada.Directories.Exists (Log_Path) then if not Silent then Ada.Text_IO.Put_Line ("Invalid config directory: " & Path); Status := Failure; end if; return; end if; -- Configure the logs Util.Log.Loggers.Initialize (Log_Path); Config_Dir := To_Unbounded_String (Path); end Set_Config_Directory; begin Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d e E o: t: c:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Set_Config_Directory (Parameter); when 'e' => Print_Env := True; when 'E' => Print_CEnv := True; when 'd' => Debug := True; when 'v' => Print_Config := True; when '*' => exit; when others => null; end case; end loop; if Length (Config_Dir) = 0 then declare Name : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Name); Dir : constant String := Containing_Directory (Path); begin Set_Config_Directory (Compose (Dir, "config"), True); Set_Config_Directory (Util.Files.Compose (Dir, "share/dynamo/base"), True); Set_Config_Directory (Gen.Configs.CONFIG_DIR, True); end; end if; if Status /= Success then Gen.Commands.Short_Help_Usage; Ada.Command_Line.Set_Exit_Status (Status); return; end if; if Ada.Command_Line.Argument_Count = 0 then Gen.Commands.Short_Help_Usage; Set_Exit_Status (Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Cmd : Gen.Commands.Command_Access; Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, To_String (Out_Dir)); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir, Debug); if Print_Config then Print_Configuration (Generator); return; elsif Print_Env then Print_Environment (Generator, False); return; elsif Print_CEnv then Print_Environment (Generator, True); return; end if; Cmd := Gen.Commands.Find_Command (Cmd_Name); -- Check that the command exists. if Cmd = null then if Cmd_Name'Length > 0 then Ada.Text_IO.Put_Line ("Invalid command: '" & Cmd_Name & "'"); end if; Gen.Commands.Short_Help_Usage; Set_Exit_Status (Failure); return; end if; Cmd.Execute (Generator); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Gen.Commands.Short_Help_Usage; Ada.Command_Line.Set_Exit_Status (2); when E : Gen.Generator.Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : Sax.Readers.XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end Dynamo;
Define two new options -e and -E to print the environment setup for ADA_PROJECT_PATH according to Dynamo installation
Define two new options -e and -E to print the environment setup for ADA_PROJECT_PATH according to Dynamo installation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0f2b9a782a2f1de0dd66b0fd98e7872765ff7f9d
src/xml/util-serialize-io-xml.ads
src/xml/util-serialize-io-xml.ads
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- 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); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- 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); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- 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 Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); -- 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); -- Starts a XML array. procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type); -- Terminates a XML array. procedure End_Array (Stream : in out Output_Stream); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); 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); 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 := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); 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; 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 := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; end record; end Util.Serialize.IO.XML;
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- 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); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- 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); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- 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 Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- 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); -- Starts a XML array. procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type); -- Terminates a XML array. procedure End_Array (Stream : in out Output_Stream); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); 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); 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 := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); 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; 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 := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; end record; end Util.Serialize.IO.XML;
Declare the Write_Enum_Entity for enum image value serialization
Declare the Write_Enum_Entity for enum image value serialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9608a39d9fb941ba5725488837c0117017029bd3
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, 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 Ada.Strings.Wide_Wide_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); procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element); procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_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); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_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, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_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; -- ----------------------- -- Buffer stream -- ----------------------- -- The `Buffer_Stream` is the base type for the `Output_Buffer_Stream` -- and `Input_Buffer_Stream` types. It holds the buffer and read/write positions. type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled with private; -- Initialize the stream to read or write on the buffer. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Buffer_Stream; Size : in Positive); -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Buffer_Stream; Content : in String); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Buffer_Stream) return Buffer_Access; -- Get the number of element in the stream. function Get_Size (Stream : in Buffer_Stream) return Natural; -- Release the buffer. overriding procedure Finalize (Object : in out Buffer_Stream); -- ----------------------- -- Output buffer stream -- ----------------------- -- The `Output_Buffer_Stream` is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call `Flush` to make sure the data -- is written to the target stream. The `Flush` operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Buffer_Stream 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); -- 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 `Into` array and return the index of the -- last element (inclusive) in `Last`. 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); type Input_Buffer_Stream is limited new Buffer_Stream and 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 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); procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element); procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character); -- Read into the buffer as many bytes as possible and return in -- `last` 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); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with private; private use Ada.Streams; type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled 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; end record; type Output_Buffer_Stream is limited new Buffer_Stream and Output_Stream with record -- 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 Buffer_Stream and Input_Stream with record -- 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; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with record -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; -- 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; end Util.Streams.Buffered;
Refactor Util.Streams.Buffered - add Buffer_Stream type with base operations to manage the buffer - update Output_Buffer_Stream and Input_Buffer_Stream to use the Buffer_Stream - add the Input_Output_Buffer_Stream type
Refactor Util.Streams.Buffered - add Buffer_Stream type with base operations to manage the buffer - update Output_Buffer_Stream and Input_Buffer_Stream to use the Buffer_Stream - add the Input_Output_Buffer_Stream type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9266dede15c3b4cafe99e271315a4de0fd74cc29
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
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
591331a981f721391deac1074fccfe6b3d14c517
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- 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 Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- A role is represented by a name in security configuration files. package Security.Policies.Roles is -- 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; -- 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); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; Invalid_Name : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. -- 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; -- 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); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. overriding procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser); 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 Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- A role is represented by a name in security configuration files. package Security.Policies.Roles is -- 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; -- 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); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. -- 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; -- 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); -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. overriding procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Fix Set_Reader_Config definition
Fix Set_Reader_Config definition
Ada
apache-2.0
stcarrez/ada-security
2638c1eb58ac20f423dd4ef499d2faa902b95db5
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- 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 Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- 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); -- 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); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- 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 Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- 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); -- 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); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
dcbe97047a716c71458494ab07698f42aec30f3d
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- 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 Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * Discovery to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * Verify to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- 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); -- 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); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- 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 Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * Discovery to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * Verify to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- 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); -- 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); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Fix typo in comment
Fix typo in comment
Ada
apache-2.0
stcarrez/ada-security
f46d234a3038e7d4188f5761d36d544b1d40b425
testutil/util-tests-servers.adb
testutil/util-tests-servers.adb
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- 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 GNAT.Sockets; with Ada.Streams; with Util.Streams.Sockets; with Util.Streams.Texts; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String) is begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1); Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Stream : aliased Util.Streams.Sockets.Socket_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Stream.Open (Socket); Input.Initialize (From => Stream'Unchecked_Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => True); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Close_Socket (Socket); end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- 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 GNAT.Sockets; with Ada.Streams; with Util.Streams.Sockets; with Util.Streams.Texts; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String) is begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Address.Addr := Addresses (Get_Host_By_Name (S.Get_Host), 1); Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Stream : aliased Util.Streams.Sockets.Socket_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Stream.Open (Socket); Input.Initialize (From => Stream'Unchecked_Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => True); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Close_Socket (Socket); end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
Use Get_Host function to find the server host name
Use Get_Host function to find the server host name
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7a0cedfdeae0e3579cab0530de68ef20756f9687
mat/src/mat-targets.adb
mat/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Readers; package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Targets.Readers.Initialize (Target => Target, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); end if; end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Readers; package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Targets.Readers.Initialize (Target => Target, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); end if; end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target.Options.Address); end Start; end MAT.Targets;
Implement the Start procedure
Implement the Start procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8bd1a63551e8fa78f195acfc852c288c239caaf2
tools/druss-commands-status.adb
tools/druss-commands-status.adb
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.0.address", "x")); Console.End_Row; N := N + 1; Gateway.IPtv.Save_Properties ("iptv" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 15); Console.Print_Title (F_WAN_IP, "WAN IP", 15); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Do_Status; -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Do_Status (Args, Context); end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("status: Control and get status about the Bbox Wifi"); Put_Line ("Usage: wifi {<action>} [<parameters>]"); New_Line; Put_Line (" status [IP]... Turn ON the wifi on the Bbox."); Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox."); Put_Line (" wifi show Show information about the wifi on the Bbox."); Put_Line (" wifi devices Show the wifi devices which are connected."); end Help; end Druss.Commands.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.0.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.length", "x")); Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", "")); Print_Uptime (Console, F_UPTIME, Gateway.Device.Get ("device.uptime", "")); Console.End_Row; N := N + 1; Gateway.Hosts.Save_Properties ("sum-" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 16); Console.Print_Title (F_WAN_IP, "WAN IP", 16); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.Print_Title (F_UPTIME, "Uptime", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Status; -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Do_Status (Args, Context); end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("status: Control and get status about the Bbox Wifi"); Put_Line ("Usage: wifi {<action>} [<parameters>]"); New_Line; Put_Line (" status [IP]... Turn ON the wifi on the Bbox."); Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox."); Put_Line (" wifi show Show information about the wifi on the Bbox."); Put_Line (" wifi devices Show the wifi devices which are connected."); end Help; end Druss.Commands.Status;
Add more useful information for the device command
Add more useful information for the device command
Ada
apache-2.0
stcarrez/bbox-ada-api
12abbdf7222305743b4deb4e0f513ea674b47305
awa/src/awa.ads
awa/src/awa.ads
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package AWA is pragma Preelaborate; -- Library SVN identification SVN_URL : constant String := "$HeadURL: file:///opt/repository/svn/ada/awa/trunk/src/awa.ads $"; -- Revision used (must run 'make version' to update) SVN_REV : constant String := "$Rev: 318 $"; end AWA;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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. ----------------------------------------------------------------------- package AWA is pragma Pure; -- Library SVN identification SVN_URL : constant String := "$HeadURL: file:///opt/repository/svn/ada/awa/trunk/src/awa.ads $"; -- Revision used (must run 'make version' to update) SVN_REV : constant String := "$Rev: 318 $"; end AWA;
Make the package Pure
Make the package Pure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f8f640bf8efca2943ca47a56cba33aaf72153b60
src/port_specification-makefile.adb
src/port_specification-makefile.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Text_IO; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package TIO renames Ada.Text_IO; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String; osmajor : String; osversion : String; option_string : String; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1); procedure send (varname : String; crate : list_crate.Map); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure dump_list (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); procedure dump_ext_zip (position : string_crate.Cursor); procedure dump_ext_7z (position : string_crate.Cursor); procedure dump_ext_lha (position : string_crate.Cursor); -- procedure dump_ext_HT (position : string_crate.Cursor); write_to_file : constant Boolean := (output_file /= ""); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & "yes"); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is begin if crate.Is_Empty then return; end if; case flavor is when 1 => send (varname & "=", True); crate.Iterate (Process => print_item'Access); send (""); when 2 => varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); when 3 => crate.Iterate (Process => dump_ext_zip'Access); when 4 => crate.Iterate (Process => dump_ext_7z'Access); when 5 => crate.Iterate (Process => dump_ext_lha'Access); when others => null; end case; end send; procedure send (varname : String; crate : list_crate.Map) is begin varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_list'Access); end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end dump_list; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send (" ", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure dump_distfiles (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign; begin send (NDX & HT.USS (string_crate.Element (position))); end dump_distfiles; procedure dump_ext_zip (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo"); send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}"); end dump_ext_zip; procedure dump_ext_7z (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_7z; procedure dump_ext_lha (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_lha; -- procedure dump_ext_HT (position : string_crate.Cursor) -- is -- index : Natural := string_crate.To_Index (position); -- begin -- end dump_ext_HT; begin if not specs.variant_exists (variant) then TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!"); return; end if; if write_to_file then TIO.Create (File => makefile_handle, Mode => TIO.Out_File, Name => output_file); end if; -- TODO: Check these to see if they are actually used. -- The pkg manifests did use many of these, but they will be generated by ravenadm send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF); send ("NAMEBASE", HT.USS (specs.namebase)); send ("VERSION", HT.USS (specs.version)); send ("REVISION", specs.revision, 0); send ("EPOCH", specs.epoch, 0); send ("KEYWORDS", specs.keywords); -- probably remove send ("VARIANT", variant); send ("DL_SITES", specs.dl_sites); send ("DISTFILE", specs.distfiles, 2); send ("DIST_SUBDIR", specs.dist_subdir); send ("DISTNAME", specs.distname); send ("DF_INDEX", specs.df_index); send ("EXTRACT_ONLY", specs.extract_only); send ("ZIP-EXTRACT", specs.extract_zip, 3); send ("7Z-EXTRACT", specs.extract_7z, 4); send ("LHA-EXTRACT", specs.extract_lha, 5); send ("NO_BUILD", specs.skip_build, True); send ("SINGLE_JOB", specs.single_job, True); send ("DESTDIR_VIA_ENV", specs.destdir_env, True); send ("BUILD_WRKSRC", specs.build_wrksrc); send ("MAKEFILE", specs.makefile); send ("MAKE_ENV", specs.make_env); send ("MAKE_ARGS", specs.make_args); send ("CFLAGS", specs.cflags); -- TODO: This is not correct, placeholder. rethink. send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation); if write_to_file then TIO.Close (makefile_handle); end if; exception when others => if TIO.Is_Open (makefile_handle) then TIO.Close (makefile_handle); end if; end generator; end Port_Specification.Makefile;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Text_IO; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package TIO renames Ada.Text_IO; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String; osmajor : String; osversion : String; option_string : String; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1); procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure dump_list (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); procedure dump_ext_zip (position : string_crate.Cursor); procedure dump_ext_7z (position : string_crate.Cursor); procedure dump_ext_lha (position : string_crate.Cursor); procedure dump_extract_head_tail (position : list_crate.Cursor); write_to_file : constant Boolean := (output_file /= ""); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & "yes"); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is begin if crate.Is_Empty then return; end if; case flavor is when 1 => send (varname & "=", True); crate.Iterate (Process => print_item'Access); send (""); when 2 => varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); when 3 => crate.Iterate (Process => dump_ext_zip'Access); when 4 => crate.Iterate (Process => dump_ext_7z'Access); when 5 => crate.Iterate (Process => dump_ext_lha'Access); when others => null; end case; end send; procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1) is begin varname_prefix := HT.SUS (varname); case flavor is when 1 => crate.Iterate (Process => dump_list'Access); when 6 => crate.Iterate (Process => dump_extract_head_tail'Access); when others => null; end case; end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end dump_list; procedure dump_extract_head_tail (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin if not list_crate.Element (position).list.Is_Empty then send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end if; end dump_extract_head_tail; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send (" ", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure dump_distfiles (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign; begin send (NDX & HT.USS (string_crate.Element (position))); end dump_distfiles; procedure dump_ext_zip (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo"); send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}"); end dump_ext_zip; procedure dump_ext_7z (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_7z; procedure dump_ext_lha (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_lha; begin if not specs.variant_exists (variant) then TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!"); return; end if; if write_to_file then TIO.Create (File => makefile_handle, Mode => TIO.Out_File, Name => output_file); end if; -- TODO: Check these to see if they are actually used. -- The pkg manifests did use many of these, but they will be generated by ravenadm send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF); send ("NAMEBASE", HT.USS (specs.namebase)); send ("VERSION", HT.USS (specs.version)); send ("REVISION", specs.revision, 0); send ("EPOCH", specs.epoch, 0); send ("KEYWORDS", specs.keywords); -- probably remove send ("VARIANT", variant); send ("DL_SITES", specs.dl_sites); send ("DISTFILE", specs.distfiles, 2); send ("DIST_SUBDIR", specs.dist_subdir); send ("DISTNAME", specs.distname); send ("DF_INDEX", specs.df_index); send ("EXTRACT_ONLY", specs.extract_only); send ("ZIP-EXTRACT", specs.extract_zip, 3); send ("7Z-EXTRACT", specs.extract_7z, 4); send ("LHA-EXTRACT", specs.extract_lha, 5); send ("EXTRACT_HEAD", specs.extract_head, 6); send ("EXTRACT_TAIL", specs.extract_tail, 6); send ("NO_BUILD", specs.skip_build, True); send ("SINGLE_JOB", specs.single_job, True); send ("DESTDIR_VIA_ENV", specs.destdir_env, True); send ("BUILD_WRKSRC", specs.build_wrksrc); send ("MAKEFILE", specs.makefile); send ("MAKE_ENV", specs.make_env); send ("MAKE_ARGS", specs.make_args); send ("CFLAGS", specs.cflags); -- TODO: This is not correct, placeholder. rethink. send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation); if write_to_file then TIO.Close (makefile_handle); end if; exception when others => if TIO.Is_Open (makefile_handle) then TIO.Close (makefile_handle); end if; end generator; end Port_Specification.Makefile;
Support EXTRACT_HEAD/EXTRACT_TAIL in makefile generation
Support EXTRACT_HEAD/EXTRACT_TAIL in makefile generation
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
231c863041b517957bafe03eed07e05f25ddca25
samples/beans/users.adb
samples/beans/users.adb
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- 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 ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.OpenID; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.OpenID; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; procedure Remove_Cookie (Name : in String); -- ------------------------------ -- 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 is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- 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 ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.Auth; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.Auth; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; procedure Remove_Cookie (Name : in String); -- ------------------------------ -- 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 is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.Auth.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Auth.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.Auth.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Auth.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
Use the Security.Auth implementation
Use the Security.Auth implementation
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
d5a743cf1861ed01b7fb8cc827821d4b3f691447
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Named Queries == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application by using named queries. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database. -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by Dynamo to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by Dynamo. -- -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- === SQL Result Mapping === -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify any table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is -- Exception raised when a query does not exist or is empty. Query_Error : exception; type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Named Queries == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application by using named queries. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database. -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by Dynamo code generator to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being -- identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query -- associated with a query name, -- * The application uses the `List` procedure generated by Dynamo. -- -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- === SQL Result Mapping === -- The XML query mapping is very close to the database XML table mapping. -- The difference is that there is no need to specify any table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record and it will instantiate the Ada container `Vectors` -- generic to provide a support for vectors of the record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- package User_Info_Vectors is -- new Ada.Containers.Vectors (Index_Type => Natural, -- Element_Type => User_Info, -- "=" => "="); -- subtype User_Info_Vector is User_Info_Vectors.Vector; -- end Samples.Model; -- -- A `List` operation is also generated and can be used to execute an SQL query and have -- the result mapped in the record. -- -- The same query mapping can be used by different queries. -- -- After writing or updating a query mapping, it is necessary to launch the -- Dynamo code generator to generate the corresponding Ada model. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query-mapping> -- <query name='user-list' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- SELECT u.name, u.email FROM user AS u -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- SELECT COUNT(*) FROM user AS u -- </sql-count> -- </query> -- </query-mapping> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. -- -- The `sql` and `sql-count` XML element can have an optional `driver` attribute. -- When defined, the attribute indicates the database driver name that is specific -- to the query. When empty or not defined, the SQL is not specific to a database driver. -- -- For each query, the Dynamo code generator generates a query definition instance which -- can be used in the Ada code to be able to use the query. Such instance is static and -- readonly and serves as a reference when using the query. For the above query, -- the Dynamo code generator generates: -- -- package Samples.User.Model is -- Query_User_List : constant ADO.Queries.Query_Definition_Access; -- private -- ... -- end Samples.User.Model; -- -- When a new query is added, the Dynamo code generator must be launched to update -- the generated Ada code. -- -- === Using Named Queries === -- In order to use a named query, it is necessary to create a query context instance -- and initialize it. The query context holds the information about the query definition -- as well as the parameters to execute the query. It provides a `Set_Query` and -- `Set_Count_Query` operation that allows to configure the named query to be executed. -- It also provides all the `Bind_Param` and `Add_Param` operations to allow giving the -- query parameters. -- -- with ADO.Sessions; -- with ADO.Queries; -- ... -- Session : ADO.Sessions.Session := Factory.Get_Session; -- Query : ADO.Queries.Context; -- Users : Samples.User.Model.User_Info_Vector; -- ... -- Query.Set_Query (Samples.User.Model.Query_User_List); -- Samples.User.Model.List (Users, Session, Query); -- -- To use the `sql-count` part of the query, you will use the `Set_Count_Query` -- with the same query definition. You will then create a query statement from the -- named query context and run the query. Since the query is expected to contain exactly -- one row, you can use the `Get_Result_Integer` to get the first row and column result. -- For example: -- -- Query.Set_Count_Query (Samples.User.Model.Query_User_List); -- ... -- Stmt : ADO.Statements.Query_Statement -- := Session.Create_Statement (Query); -- ... -- Stmt.Execute; -- ... -- Count : Natural := Stmt.Get_Result_Integer; -- -- You may also use the `ADO.Datasets.Get_Count` operation which simplifies these steps -- in: -- -- Query.Set_Count_Query (Samples.User.Model.Query_User_List); -- ... -- Count : Natural := ADO.Datasets.Get_Count (Session, Query); -- package ADO.Queries is -- Exception raised when a query does not exist or is empty. Query_Error : exception; type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
Clarify documentation on named queries
Clarify documentation on named queries
Ada
apache-2.0
stcarrez/ada-ado
0caf99a0afc796e7db7a3eda01f8a14f15d19992
src/gen-utils.ads
src/gen-utils.ads
----------------------------------------------------------------------- -- gen-utils -- Utilities for model generator -- 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.Strings.Unbounded; with Ada.Containers.Ordered_Sets; with Ada.Containers.Indefinite_Vectors; with DOM.Core; package Gen.Utils is -- Generic procedure to iterate over the DOM nodes children of <b>node</b> -- and having the entity name <b>name</b>. generic type T is limited private; with procedure Process (Closure : in out T; Node : DOM.Core.Node); procedure Iterate_Nodes (Closure : in out T; Node : in DOM.Core.Node; Name : in String; Recurse : in Boolean := True); -- Get the first DOM child from the given entity tag function Get_Child (Node : in DOM.Core.Node; Name : in String) return DOM.Core.Node; -- Get the content of the node function Get_Data_Content (Node : in DOM.Core.Node) return String; -- Get the content of the node identified by <b>Name</b> under the given DOM node. function Get_Data_Content (Node : in DOM.Core.Node; Name : in String) return String; -- Get a boolean attribute function Get_Attribute (Node : in DOM.Core.Node; Name : in String; Default : in Boolean := False) return Boolean; -- Get a string attribute function Get_Attribute (Node : in DOM.Core.Node; Name : in String; Default : in String := "") return String; -- Get the Ada package name from a qualified type function Get_Package_Name (Name : in String) return String; -- Get the Ada type name from a full qualified type function Get_Type_Name (Name : in String) return String; -- Get a query name from the XML query file name function Get_Query_Name (Path : in String) return String; use Ada.Strings.Unbounded; package String_Set is new Ada.Containers.Ordered_Sets (Element_Type => Ada.Strings.Unbounded.Unbounded_String, "<" => Ada.Strings.Unbounded."<", "=" => Ada.Strings.Unbounded."="); package String_List is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String, "=" => "="); -- Returns True if the Name is a valid project or module name. -- The name must be a valid Ada identifier. function Is_Valid_Name (Name : in String) return Boolean; end Gen.Utils;
----------------------------------------------------------------------- -- gen-utils -- Utilities for model generator -- 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.Strings.Unbounded; with Ada.Containers.Ordered_Sets; with Ada.Containers.Indefinite_Vectors; with DOM.Core; package Gen.Utils is -- Generic procedure to iterate over the DOM nodes children of <b>node</b> -- and having the entity name <b>name</b>. generic type T (<>) is limited private; with procedure Process (Closure : in out T; Node : DOM.Core.Node); procedure Iterate_Nodes (Closure : in out T; Node : in DOM.Core.Node; Name : in String; Recurse : in Boolean := True); -- Get the first DOM child from the given entity tag function Get_Child (Node : in DOM.Core.Node; Name : in String) return DOM.Core.Node; -- Get the content of the node function Get_Data_Content (Node : in DOM.Core.Node) return String; -- Get the content of the node identified by <b>Name</b> under the given DOM node. function Get_Data_Content (Node : in DOM.Core.Node; Name : in String) return String; -- Get a boolean attribute function Get_Attribute (Node : in DOM.Core.Node; Name : in String; Default : in Boolean := False) return Boolean; -- Get a string attribute function Get_Attribute (Node : in DOM.Core.Node; Name : in String; Default : in String := "") return String; -- Get the Ada package name from a qualified type function Get_Package_Name (Name : in String) return String; -- Get the Ada type name from a full qualified type function Get_Type_Name (Name : in String) return String; -- Get a query name from the XML query file name function Get_Query_Name (Path : in String) return String; use Ada.Strings.Unbounded; package String_Set is new Ada.Containers.Ordered_Sets (Element_Type => Ada.Strings.Unbounded.Unbounded_String, "<" => Ada.Strings.Unbounded."<", "=" => Ada.Strings.Unbounded."="); package String_List is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String, "=" => "="); -- Returns True if the Name is a valid project or module name. -- The name must be a valid Ada identifier. function Is_Valid_Name (Name : in String) return Boolean; end Gen.Utils;
Allow to use indefinite types for the generic iterate operation
Allow to use indefinite types for the generic iterate operation
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
0e420688451ab5446429a5529b1ffc3700d95487
regtests/el-expressions-tests.adb
regtests/el-expressions-tests.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- 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 AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; with Action_Bean; with Ada.Text_IO; with Ada.Strings.Unbounded; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; use Ada.Strings.Unbounded; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Simple_Evaluation (T : in out Test) is begin Check (T, "#{true}", "TRUE"); Check (T, "#{false}", "FALSE"); Check (T, "#{not false}", "TRUE"); Check (T, "#{! false}", "TRUE"); Check (T, "#{4 * 3}", "12"); Check (T, "#{12 / 3}", "4"); Check (T, "#{12 div 3}", "4"); Check (T, "#{3 % 2}", "1"); Check (T, "#{3 mod 2}", "1"); Check (T, "#{3 > 4 ? 1 : 2}", "2"); Check (T, "#{3 < 4 ? 1 : 2}", "1"); Check (T, "#{true and false}", "FALSE"); Check (T, "#{true or false}", "TRUE"); Check (T, "#{- 23}", "-23"); Check (T, "#{1.0}", "1"); Check (T, "#{'\\''}", "'"); end Test_Simple_Evaluation; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user ne null}", "TRUE"); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", "42"); Check (T, "#{user.age le 42}", "TRUE"); Check (T, "#{user.age lt 44}", "TRUE"); Check (T, "#{user.age ge 42}", "TRUE"); Check (T, "#{user.age ge 45}", "FALSE"); Check (T, "#{user.age gt 42}", "FALSE"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", "43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "#{user.firstName eq 'Joe'}", "TRUE"); Check (T, "#{user.firstName ne 'Joe'}", "FALSE"); Check (T, "#{user.firstName eq 'Boe' or user.firstName eq 'Joe'}", "TRUE"); Check (T, "Joe is #{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); Check_Error (T, "#{12 > 23 ? 44}"); end Test_Parse_Error; -- Test evaluation of method expression procedure Test_Method_Evaluation (T : in out Test) is use Action_Bean; A1 : constant Action_Access := new Action; A2 : constant Action_Access := new Action; P : constant Person_Access := Create_Person ("Joe", "Black", 42); M : EL.Expressions.Method_Expression := Create_Expression (Context => T.Context, Expr => "#{action.notify}"); begin T.Context.Set_Variable ("action", A1); Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, P.Last_Name = A1.Person.Last_Name, "Name was not set"); P.Last_Name := To_Unbounded_String ("John"); T.Context.Set_Variable ("action", A2); Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, "John" = A2.Person.Last_Name, "Name was not set"); end Test_Method_Evaluation; -- Test evaluation of method expression procedure Test_Invalid_Method (T : in out Test) is use Action_Bean; A1 : constant Action_Access := new Action; A2 : constant Action_Access := new Action; P : constant Person_Access := Create_Person ("Joe", "Black", 42); M2 : EL.Expressions.Method_Expression; M : EL.Expressions.Method_Expression := Create_Expression (Context => T.Context, Expr => "#{action.bar}"); begin -- Bean is not found begin Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, False, "The Invalid_Variable exception was not raised"); exception when EL.Expressions.Invalid_Variable => null; end; T.Context.Set_Variable ("action", A1); begin Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, False, "The Invalid_Method exception was not raised"); exception when EL.Expressions.Invalid_Method => null; end; -- M2 is not initialized, this should raise Invalid_Expression begin Proc_Action.Execute (M2, Person (P.all), T.Context); Assert (T, False, "The Invalid_Method exception was not raised"); exception when EL.Expressions.Invalid_Expression => null; end; -- Create a method expression with an invalid expression begin M := Create_Expression ("#{12+13}", T.Context); Assert (T, False, "The Invalid_Expression exception was not raised"); exception when EL.Expressions.Invalid_Expression => null; end; end Test_Invalid_Method; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value (constant expressions)", Test_Simple_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Method_Info", Test_Method_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Method_Info (Invalid_method)", Test_Invalid_Method'Access)); end Add_Tests; end EL.Expressions.Tests;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- 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 AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; with Action_Bean; with Ada.Text_IO; with Ada.Strings.Unbounded; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; use Ada.Strings.Unbounded; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Simple_Evaluation (T : in out Test) is begin Check (T, "#{true}", "TRUE"); Check (T, "#{false}", "FALSE"); Check (T, "#{not false}", "TRUE"); Check (T, "#{! false}", "TRUE"); Check (T, "#{4 * 3}", "12"); Check (T, "#{12 / 3}", "4"); Check (T, "#{12 div 3}", "4"); Check (T, "#{3 % 2}", "1"); Check (T, "#{3 mod 2}", "1"); Check (T, "#{3 <= 2}", "FALSE"); Check (T, "#{3 < 2}", "FALSE"); Check (T, "#{3 > 2}", "TRUE"); Check (T, "#{3 >= 2}", "TRUE"); Check (T, "#{3 >= 2 && 2 >= 3}", "FALSE"); Check (T, "#{3 >= 4 || 2 < 3}", "TRUE"); Check (T, "#{3 > 4 ? 1 : 2}", "2"); Check (T, "#{3 < 4 ? 1 : 2}", "1"); Check (T, "#{true and false}", "FALSE"); Check (T, "#{true or false}", "TRUE"); Check (T, "#{- 23}", "-23"); Check (T, "#{1.0}", "1"); Check (T, "#{'a\\'b'}", "'"); end Test_Simple_Evaluation; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user ne null}", "TRUE"); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", "42"); Check (T, "#{user.age le 42}", "TRUE"); Check (T, "#{user.age lt 44}", "TRUE"); Check (T, "#{user.age ge 42}", "TRUE"); Check (T, "#{user.age ge 45}", "FALSE"); Check (T, "#{user.age gt 42}", "FALSE"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", "43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "#{user.firstName eq 'Joe'}", "TRUE"); Check (T, "#{user.firstName ne 'Joe'}", "FALSE"); Check (T, "#{user.firstName eq 'Boe' or user.firstName eq 'Joe'}", "TRUE"); Check (T, "Joe is #{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); Check_Error (T, "#{12 > 23 ? 44}"); Check_Error (T, "#{"); Check_Error (T, "${(12+1}"); Check_Error (T, "#{'\\''}"); end Test_Parse_Error; -- Test evaluation of method expression procedure Test_Method_Evaluation (T : in out Test) is use Action_Bean; A1 : constant Action_Access := new Action; A2 : constant Action_Access := new Action; P : constant Person_Access := Create_Person ("Joe", "Black", 42); M : EL.Expressions.Method_Expression := Create_Expression (Context => T.Context, Expr => "#{action.notify}"); begin T.Context.Set_Variable ("action", A1); Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, P.Last_Name = A1.Person.Last_Name, "Name was not set"); P.Last_Name := To_Unbounded_String ("John"); T.Context.Set_Variable ("action", A2); Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, "John" = A2.Person.Last_Name, "Name was not set"); end Test_Method_Evaluation; -- Test evaluation of method expression procedure Test_Invalid_Method (T : in out Test) is use Action_Bean; A1 : constant Action_Access := new Action; A2 : constant Action_Access := new Action; P : constant Person_Access := Create_Person ("Joe", "Black", 42); M2 : EL.Expressions.Method_Expression; M : EL.Expressions.Method_Expression := Create_Expression (Context => T.Context, Expr => "#{action.bar}"); begin -- Bean is not found begin Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, False, "The Invalid_Variable exception was not raised"); exception when EL.Expressions.Invalid_Variable => null; end; T.Context.Set_Variable ("action", A1); begin Proc_Action.Execute (M, Person (P.all), T.Context); Assert (T, False, "The Invalid_Method exception was not raised"); exception when EL.Expressions.Invalid_Method => null; end; -- M2 is not initialized, this should raise Invalid_Expression begin Proc_Action.Execute (M2, Person (P.all), T.Context); Assert (T, False, "The Invalid_Method exception was not raised"); exception when EL.Expressions.Invalid_Expression => null; end; -- Create a method expression with an invalid expression begin M := Create_Expression ("#{12+13}", T.Context); Assert (T, False, "The Invalid_Expression exception was not raised"); exception when EL.Expressions.Invalid_Expression => null; end; end Test_Invalid_Method; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value (constant expressions)", Test_Simple_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Method_Info", Test_Method_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Method_Info (Invalid_method)", Test_Invalid_Method'Access)); end Add_Tests; end EL.Expressions.Tests;
Add new EL tests
Add new EL tests
Ada
apache-2.0
stcarrez/ada-el
8906620cdd58e14d8a9e22a57fa9d7cfb74ff6fc
awa/plugins/awa-images/src/awa-images-beans.adb
awa/plugins/awa-images/src/awa-images-beans.adb
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in Image_List_Bean) is use AWA.Services; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; overriding procedure Load (Into : in out Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Images.Models.Query_Image_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Image_Bean bean instance. -- ------------------------------ function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Image_Bean_Access := new Image_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Image_Bean; end AWA.Images.Beans;
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in Image_List_Bean) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; overriding procedure Load (Into : in out Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Images.Models.Query_Image_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Image_Bean bean instance. -- ------------------------------ function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Image_Bean_Access := new Image_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Image_Bean; end AWA.Images.Beans;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
68e366fa393978627f530ecf966622af5e067f74
awa/regtests/awa-users-services-tests.adb
awa/regtests/awa-users-services-tests.adb
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Modules; with AWA.Tests.Helpers.Users; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test, "Users.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); AWA.Tests.Helpers.Users.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin AWA.Tests.Helpers.Users.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : AWA.Tests.Helpers.Users.Test_User; T1 : Ada.Calendar.Time; begin begin Principal.Email.Set_Email ("[email protected]"); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user T1 := Ada.Calendar.Clock; AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type AWA.Users.Principals.Principal_Access; Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); AWA.Tests.Helpers.Users.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", Principal => Principal.Principal); T.Assert (Principal.Principal /= null, "No principal returned"); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); AWA.Tests.Helpers.Users.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Modules.User_Module_Access; begin declare M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Modules.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Modules.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Modules; with AWA.Tests.Helpers.Users; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test, "Users.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); AWA.Tests.Helpers.Users.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin AWA.Tests.Helpers.Users.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : AWA.Tests.Helpers.Users.Test_User; T1 : Ada.Calendar.Time; begin begin Principal.Email.Set_Email ("[email protected]"); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user T1 := Ada.Calendar.Clock; AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type AWA.Users.Principals.Principal_Access; Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); AWA.Tests.Helpers.Users.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", Principal => Principal.Principal); T.Assert (Principal.Principal /= null, "No principal returned"); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); AWA.Tests.Helpers.Users.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Modules.User_Module_Access; begin declare M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Modules.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Modules.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
08b990e9f6a295181d30b04e45d01b9a8b563f7f
src/sys/os-unix/util-processes-os.adb
src/sys/os-unix/util-processes-os.adb
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; use type Ada.Directories.File_Kind; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- 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 File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; 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; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; 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 (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; 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 Interfaces.C.Strings.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 := Interfaces.C.Strings.New_String (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 Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; -- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected. if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; -- Redirect stdin to the pipe unless we use file redirection. if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); end if; end if; if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Close (Stdin_Pipes (0)); end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (1)); end if; -- Redirect stdout to the pipe unless we use file redirection. if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); end if; end if; if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Close (Stdout_Pipes (1)); end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (0)); end if; if Sys.Err_File = Null_Ptr and Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); end if; if Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDIN_FILENO then Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDOUT_FILENO then Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDERR_FILENO then Result := Sys_Dup2 (Fd, STDERR_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Dir /= Null_Ptr then Result := Sys_Chdir (Sys.Dir); if Result < 0 then Sys_Exit (253); end if; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- 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 := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (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 begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); Interfaces.C.Strings.Free (Sys.Dir); end Finalize; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; use type Ada.Directories.File_Kind; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- 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 File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; 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; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; 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 (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; 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 Interfaces.C.Strings.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 := Interfaces.C.Strings.New_String (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 Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; -- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected. if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE and (Mode = READ_ALL or Mode = READ_WRITE_ALL) then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; -- Redirect stdin to the pipe unless we use file redirection. if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); end if; end if; if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Close (Stdin_Pipes (0)); end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (1)); end if; -- Redirect stdout to the pipe unless we use file redirection. if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); end if; end if; if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Close (Stdout_Pipes (1)); end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (0)); end if; if Sys.Err_File = Null_Ptr and Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); end if; if Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDIN_FILENO then Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDOUT_FILENO then Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDERR_FILENO then Result := Sys_Dup2 (Fd, STDERR_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Dir /= Null_Ptr then Result := Sys_Chdir (Sys.Dir); if Result < 0 then Sys_Exit (253); end if; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- 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 := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (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 begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); Interfaces.C.Strings.Free (Sys.Dir); end Finalize; end Util.Processes.Os;
Fix READ pipe mode which was also redirecting the standard error
Fix READ pipe mode which was also redirecting the standard error
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
be54d657911244b51b27f04150b27d8bb1979412
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); end ASF.Components.Widgets.Likes;
Implement the Google like generator
Implement the Google like generator
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7cefabef6aa027d5d9b8ff4b43a84d0f6b7c51e8
awa/src/awa-applications-configs.ads
awa/src/awa-applications-configs.ads
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with Util.Serialize.IO.XML; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Reader : in out Util.Serialize.IO.XML.Parser; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean); end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with Util.Serialize.IO.XML; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Reader : in out Util.Serialize.IO.XML.Parser; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean); -- Get the configuration path for the application name. -- The configuration path is search from: -- o the current directory, -- o the 'config' directory, -- o the Dynamo installation directory in share/dynamo function Get_Config_Path (Name : in String) return String; end AWA.Applications.Configs;
Declare the Get_Config_Path function to retrieve a configuration file path
Declare the Get_Config_Path function to retrieve a configuration file path
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
04ad57ec4b5dac18a27674fc67cf71b0f05eb4b9
awa/plugins/awa-images/regtests/awa-images-tests.ads
awa/plugins/awa-images/regtests/awa-images-tests.ads
----------------------------------------------------------------------- -- awa-images-tests -- Unit tests for images module -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Servlet.requests.Mockup; with Servlet.Responses.Mockup; with Ada.Strings.Unbounded; package AWA.Images.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Folder_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the image as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the image lists contain the given image. procedure Verify_List_Contains (T : in out Test; Name : in String); -- Test access to the image as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of image by simulating web requests. procedure Test_Create_Image (T : in out Test); -- Test getting an image which does not exist. procedure Test_Missing_Image (T : in out Test); end AWA.Images.Tests;
----------------------------------------------------------------------- -- awa-images-tests -- Unit tests for images module -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Images.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Folder_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the image as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the image lists contain the given image. procedure Verify_List_Contains (T : in out Test; Name : in String); -- Test access to the image as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of image by simulating web requests. procedure Test_Create_Image (T : in out Test); -- Test getting an image which does not exist. procedure Test_Missing_Image (T : in out Test); end AWA.Images.Tests;
Remove unused with clause (moved to the body)
Remove unused with clause (moved to the body)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b40eede0e083852227ec3981585ac751a4d9081a
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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; with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use ADO.Statements; use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract tagged limited record Count : Natural := 0; 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; procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String; Id : out Identifier) 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; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- Releases the connection and all resources used to maintain it. procedure Release (Database : access Database_Connection) is abstract; -- ------------------------------ -- 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; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- 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 : Unbounded_String; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Integer := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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; with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use ADO.Statements; use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record Count : Natural := 0; 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; procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String; Id : out Identifier) 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; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- ------------------------------ -- 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; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- 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 : Unbounded_String; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Integer := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers;
Replace the Release by the Finalize method
Replace the Release by the Finalize method
Ada
apache-2.0
stcarrez/ada-ado
fbdd5ab3326c122ab428821852f3a6f02ce1a2eb
mat/src/gtk/gtkmatp.adb
mat/src/gtk/gtkmatp.adb
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Log.Loggers; with Readline; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Callbacks; with Glib.Error; with Gtk.Main; with Gtk.Widget; with Gtkada.Builder; procedure GtkMatp is Builder : Gtkada.Builder.Gtkada_Builder; Error : aliased Glib.Error.GError; Result : Glib.Guint; Main : Gtk.Widget.Gtk_Widget; begin Gtk.Main.Init; Util.Log.Loggers.Initialize ("matp.properties"); Gtkada.Builder.Gtk_New (Builder); Result := Builder.Add_From_File ("mat.glade", Error'Access); Builder.Do_Connect; MAT.Callbacks.Initialize (Builder); Main := Gtk.Widget.Gtk_Widget (Builder.Get_Object ("main")); Main.Show_All; Gtk.Main.Main; end GtkMatp;
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Targets.Gtkmat; with Gtk.Main; with Gtk.Widget; procedure GtkMatp is Main : Gtk.Widget.Gtk_Widget; Target : MAT.Targets.Gtkmat.Target_Type; begin Target.Initialize_Options; Target.Initialize_Widget (Main); MAT.Commands.Initialize_Files (Target); Target.Start; MAT.Commands.Interactive (Target); Target.Stop; Gtk.Main.Main; end GtkMatp;
Update the Gtk MAT application to use the MAT.Targets.Gtkmat Target_Type support
Update the Gtk MAT application to use the MAT.Targets.Gtkmat Target_Type support
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e924ff3f1138299f4ca971890cd1ef99c52500a8
src/asf-components-widgets-likes.ads
src/asf-components-widgets-likes.ads
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with record App_Id : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with record App_Id : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
Define the Google_Like_Generator type
Define the Google_Like_Generator type
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
4a3f0fba38a44c4fff572e105e914f861d3e91f0
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, 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;
----------------------------------------------------------------------- -- 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 (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.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;
Rename Finalize parameter into Stream
Rename Finalize parameter into Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0f738bafab2c106bb12ea32f6850a873998d3f97
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ce88a106b9bf9ff462d0d2977c338d533c216828
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ADO.Drivers.Connections; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; -- Query_List : Query_Definition_Access := null; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Query.File := File; Query.Next := File.Queries; File.Queries := Query; if File.Next = null and then Query_Files /= File then File.Next := Query_Files; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (Query : in Query_Definition_Access) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if Query.File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (Query); begin if Query.File.Last_Modified = M then return False; end if; Query.File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Into : in Query_File_Access) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Access; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; Into.Query := null; if Into.Query_Def /= null then Into.Query := new Query_Info; Into.Query_Def.Query := Into.Query; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading XML query {0}", Into.Path.all); Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Reader, Loader'Access); -- Read the XML query file. Reader.Parse (Into.Path.all); Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Into.Path.all); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Into : in Query_Definition_Access) is begin if Into.Query = null or else Is_Modified (Into) then Read_Query (Into.File); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Paths : in String; Load : in Boolean) is procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Ada.Strings.Unbounded.String_Access); File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Free (File.Path); File.Path := new String '(Path); if Load then Read_Query (File); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body Query is begin Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ADO.Drivers.Connections; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Query.File := File; Query.Next := File.Queries; File.Queries := Query; if File.Next = null and then Query_Files /= File then File.Next := Query_Files; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (Query : in Query_Definition_Access) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if Query.File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (Query); begin if Query.File.Last_Modified = M then return False; end if; Query.File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Into : in Query_File_Access) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Access; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; Into.Query := null; if Into.Query_Def /= null then Into.Query := new Query_Info; Into.Query_Def.Query := Into.Query; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading XML query {0}", Into.Path.all); Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Reader, Loader'Access); -- Read the XML query file. Reader.Parse (Into.Path.all); Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Into.Path.all); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Into : in Query_Definition_Access) is begin if Into.Query = null or else Is_Modified (Into) then Read_Query (Into.File); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Paths : in String; Load : in Boolean) is procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Ada.Strings.Unbounded.String_Access); File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Free (File.Path); File.Path := new String '(Path); if Load then Read_Query (File); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body Query is begin Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Remove unused code
Remove unused code
Ada
apache-2.0
Letractively/ada-ado
99f7604ffab49da16c0bda2dc4f6fe12ad453406
demo/shaders.adb
demo/shaders.adb
--------------------------------------------------------------------------- -- -- A minimal example of vertex and fragment shaders -- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- -- Copyright (c) 2011, David Bouchain <[email protected]> -- -- Permission to use, copy, modify, and/or distribute this software -- for any purpose with or without fee is hereby granted, provided -- that the above copyright notice and this permission notice appear -- in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -- WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -- AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -- CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -- NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- -- This program requires OpenGL 2.0 or later. -- -- The expected output is a blue quad in the center of the window -- with the same proportions as the window. If the window is -- completely white, something went wrong with the shaders. -- --------------------------------------------------------------------------- with System; with Ada.Characters.Latin_1; with Lumen.Window; with Lumen.Events; with Lumen.Events.Animate; with Lumen.GL; with Lumen.Binary; procedure Shaders is -- Keystrokes we care about Escape : constant Lumen.Events.Key_Symbol := Lumen.Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC)); Letter_q : constant Lumen.Events.Key_Symbol := Lumen.Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LC_Q)); ------------------------------------------------------------------------ -- -- These are the 'names' of the vertex shader, the fragment -- shader, and the shader program, respectively. They serve as -- handles to the internal objects in the OpenGL implementation. -- Vertex_Shader : Lumen.GL.Uint; Fragment_Shader : Lumen.GL.Uint; Shader_Program : Lumen.GL.Uint; ------------------------------------------------------------------------ -- -- This is the window handle of our application window. -- Win : Lumen.Window.Window_Handle; -- The master event-loop flag Terminated : Boolean := False; ------------------------------------------------------------------------ -- -- This draws a quad that would normally cover the whole -- window. It is set to be drawn in white. However, the vertex -- shader scales by 0.5 and the fragment shader outputs a constant -- color, so the result is a smaller quad in blue. -- procedure Render_Scene is use Lumen.GL; begin Clear_Color (0.0, 0.0, 0.0, 1.0); Clear (GL_COLOR_BUFFER_BIT); Matrix_Mode (GL_MODELVIEW); Load_Identity; Color (Float (1.0), 1.0, 1.0, 1.0); Begin_Primitive (GL_QUADS); Vertex (Float (-1.0), -1.0); Vertex (Float (1.0), -1.0); Vertex (Float (1.0), 1.0); Vertex (Float (-1.0), 1.0); End_Primitive; Lumen.Window.Swap (Win); end Render_Scene; ------------------------------------------------------------------------ -- -- This sets the viewport and re-renders the scene. We don't touch -- the projection matrix so it is left as identity. -- procedure Resize_Scene (Width, Height : Natural) is begin Lumen.GL.Viewport (0, 0, Width, Height); Render_Scene; end Resize_Scene; ---------------------------------------------------------------------------- -- Callback triggered by the Resized event; tell OpenGL that the -- user has resized the window procedure Resize_Handler (Height : in Integer; Width : in Integer) is begin -- Resize_Handler -- Set the new view parameters and redraw the scene Resize_Scene (Width, Height); end Resize_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses procedure Key_Handler (Category : in Lumen.Events.Key_Category; Symbol : in Lumen.Events.Key_Symbol; Modifiers : in Lumen.Events.Modifier_Set) is use type Lumen.Events.Key_Symbol; begin -- Key_Handler if Symbol = Escape or Symbol = Letter_q then Terminated := True; end if; end Key_Handler; ---------------------------------------------------------------------------- -- Called once per frame; just re-draws the scene function New_Frame (Frame_Delta : in Duration) return Boolean is begin -- New_Frame Render_Scene; return not Terminated; end New_Frame; begin Lumen.Window.Create (Win, Name => "Minimal Shader Demo"); Win.Resize := Resize_Handler'Unrestricted_Access; Win.Key_Press := Key_Handler'Unrestricted_Access; declare use Lumen.GL; use type Lumen.Binary.Word; --------------------------------------------------------------------- -- -- These are the shader source codes which OpenGL requires as a -- set of strings. The pointers are required because OpenGL -- expects a pointer to a pointer. This is cumbersome to do in -- Ada and there should really be a minimal wrapper function, -- even in the thin binding. -- Vertex_Shader_Source : String := "attribute vec4 in_vertex;" & "void main() {" & " gl_Position = 0.5*in_vertex;" & " gl_Position.w = 1.0;" & "}" & Character'Val (0); Vertex_Shader_Source_Pointer : Pointer := Vertex_Shader_Source'Address; Fragment_Shader_Source : String := "void main() {" & " gl_FragColor = vec4(0.0, 0.0, 0.75, 1.0);" & "}" & Character'Val (0); Fragment_Shader_Source_Pointer : Pointer := Fragment_Shader_Source'Address; begin --------------------------------------------------------------------- -- -- This creates the two new shader objects, one for the vertex -- shader and one for the fragment shader. -- Vertex_Shader := Create_Shader (GL_VERTEX_SHADER); Fragment_Shader := Create_Shader (GL_FRAGMENT_SHADER); --------------------------------------------------------------------- -- -- This sends the source code strings to the GLSL compiler -- which resides in the OpenGL driver. -- Shader_Source (Vertex_Shader, 1, Vertex_Shader_Source_Pointer'Address, System'To_Address (0)); Shader_Source (Fragment_Shader, 1, Fragment_Shader_Source_Pointer'Address, System'To_Address (0)); --------------------------------------------------------------------- -- -- This compiles the shaders into GPU machine code. Error -- checks have been omitted for simplicity here. Whether or not -- the compiling was successful can be queried by -- Get_Error. Textual error messages can be retrieved through -- Get_Shader_Info_Log. -- Compile_Shader (Vertex_Shader); Compile_Shader (Fragment_Shader); --------------------------------------------------------------------- -- -- This creates the program object. -- Shader_Program := Create_Program; --------------------------------------------------------------------- -- -- This assigns the 'shader object code', which was generated by -- compiling the sources, to the shader program. -- Attach_Shader (Shader_Program, Vertex_Shader); Attach_Shader (Shader_Program, Fragment_Shader); --------------------------------------------------------------------- -- -- This links the shaders to create a complete GPU program. -- Link_Program (Shader_Program); --------------------------------------------------------------------- -- -- This sends the program to the GPU so it is used in the -- OpenGL pipeline. -- Use_Program (Shader_Program); end; Resize_Scene (Lumen.Window.Width (Win), Lumen.Window.Height (Win)); ------------------------------------------------------------------------ -- -- This enters the main loop, using the resize handler and frame procedures -- defined above as event callbacks. -- Lumen.Events.Animate.Run (Win, 24, New_Frame'Unrestricted_Access); end Shaders;
--------------------------------------------------------------------------- -- -- A minimal example of vertex and fragment shaders -- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- -- Copyright (c) 2011, David Bouchain <[email protected]> -- -- Permission to use, copy, modify, and/or distribute this software -- for any purpose with or without fee is hereby granted, provided -- that the above copyright notice and this permission notice appear -- in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -- WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -- AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -- CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -- NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- -- This program requires OpenGL 2.0 or later. -- -- The expected output is a blue quad in the center of the window -- with the same proportions as the window. If the window is -- completely white, something went wrong with the shaders. -- --------------------------------------------------------------------------- with System; with Ada.Characters.Latin_1; with Lumen.Window; with Lumen.Events; with Lumen.Events.Animate; with Lumen.GL; with Lumen.Binary; procedure Shaders is -- Keystrokes we care about Escape : constant Lumen.Events.Key_Symbol := Lumen.Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC)); Letter_q : constant Lumen.Events.Key_Symbol := Lumen.Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LC_Q)); ------------------------------------------------------------------------ -- -- These are the 'names' of the vertex shader, the fragment -- shader, and the shader program, respectively. They serve as -- handles to the internal objects in the OpenGL implementation. -- Vertex_Shader : Lumen.GL.Uint; Fragment_Shader : Lumen.GL.Uint; Shader_Program : Lumen.GL.Uint; ------------------------------------------------------------------------ -- -- This is the window handle of our application window. -- Win : Lumen.Window.Window_Handle; -- The master event-loop flag Terminated : Boolean := False; ------------------------------------------------------------------------ -- -- This draws a quad that would normally cover the whole -- window. It is set to be drawn in white. However, the vertex -- shader scales by 0.5 and the fragment shader outputs a constant -- color, so the result is a smaller quad in blue. -- procedure Render_Scene is use Lumen.GL; begin Clear_Color (0.0, 0.0, 0.0, 1.0); Clear (GL_COLOR_BUFFER_BIT); Matrix_Mode (GL_MODELVIEW); Load_Identity; Color (Float (1.0), 1.0, 1.0, 1.0); Begin_Primitive (GL_QUADS); Vertex (Float (-1.0), -1.0); Vertex (Float (1.0), -1.0); Vertex (Float (1.0), 1.0); Vertex (Float (-1.0), 1.0); End_Primitive; Lumen.Window.Swap (Win); end Render_Scene; ------------------------------------------------------------------------ -- -- This sets the viewport and re-renders the scene. We don't touch -- the projection matrix so it is left as identity. -- procedure Resize_Scene (Width, Height : in Integer) is begin Lumen.GL.Viewport (0, 0, Width, Height); Render_Scene; end Resize_Scene; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses procedure Key_Handler (Category : in Lumen.Events.Key_Category; Symbol : in Lumen.Events.Key_Symbol; Modifiers : in Lumen.Events.Modifier_Set) is use type Lumen.Events.Key_Symbol; begin -- Key_Handler if Symbol = Escape or Symbol = Letter_q then Terminated := True; end if; end Key_Handler; ---------------------------------------------------------------------------- -- Called once per frame; just re-draws the scene function New_Frame (Frame_Delta : in Duration) return Boolean is begin -- New_Frame Render_Scene; return not Terminated; end New_Frame; begin Lumen.Window.Create (Win, Name => "Minimal Shader Demo"); Win.Resize := Resize_Scene'Unrestricted_Access; Win.Key_Press := Key_Handler'Unrestricted_Access; declare use Lumen.GL; use type Lumen.Binary.Word; --------------------------------------------------------------------- -- -- These are the shader source codes which OpenGL requires as a -- set of strings. The pointers are required because OpenGL -- expects a pointer to a pointer. This is cumbersome to do in -- Ada and there should really be a minimal wrapper function, -- even in the thin binding. -- Vertex_Shader_Source : String := "attribute vec4 in_vertex;" & "void main() {" & " gl_Position = 0.5*in_vertex;" & " gl_Position.w = 1.0;" & "}" & Character'Val (0); Vertex_Shader_Source_Pointer : Pointer := Vertex_Shader_Source'Address; Fragment_Shader_Source : String := "void main() {" & " gl_FragColor = vec4(0.0, 0.0, 0.75, 1.0);" & "}" & Character'Val (0); Fragment_Shader_Source_Pointer : Pointer := Fragment_Shader_Source'Address; begin --------------------------------------------------------------------- -- -- This creates the two new shader objects, one for the vertex -- shader and one for the fragment shader. -- Vertex_Shader := Create_Shader (GL_VERTEX_SHADER); Fragment_Shader := Create_Shader (GL_FRAGMENT_SHADER); --------------------------------------------------------------------- -- -- This sends the source code strings to the GLSL compiler -- which resides in the OpenGL driver. -- Shader_Source (Vertex_Shader, 1, Vertex_Shader_Source_Pointer'Address, System'To_Address (0)); Shader_Source (Fragment_Shader, 1, Fragment_Shader_Source_Pointer'Address, System'To_Address (0)); --------------------------------------------------------------------- -- -- This compiles the shaders into GPU machine code. Error -- checks have been omitted for simplicity here. Whether or not -- the compiling was successful can be queried by -- Get_Error. Textual error messages can be retrieved through -- Get_Shader_Info_Log. -- Compile_Shader (Vertex_Shader); Compile_Shader (Fragment_Shader); --------------------------------------------------------------------- -- -- This creates the program object. -- Shader_Program := Create_Program; --------------------------------------------------------------------- -- -- This assigns the 'shader object code', which was generated by -- compiling the sources, to the shader program. -- Attach_Shader (Shader_Program, Vertex_Shader); Attach_Shader (Shader_Program, Fragment_Shader); --------------------------------------------------------------------- -- -- This links the shaders to create a complete GPU program. -- Link_Program (Shader_Program); --------------------------------------------------------------------- -- -- This sends the program to the GPU so it is used in the -- OpenGL pipeline. -- Use_Program (Shader_Program); end; Resize_Scene (Lumen.Window.Width (Win), Lumen.Window.Height (Win)); ------------------------------------------------------------------------ -- -- This enters the main loop, using the resize handler and frame procedures -- defined above as event callbacks. -- Lumen.Events.Animate.Run (Win, 24, New_Frame'Unrestricted_Access); end Shaders;
Remove useless resize callback wrapper and just use original Resize_Scene procedure directly
Remove useless resize callback wrapper and just use original Resize_Scene procedure directly
Ada
isc
darkestkhan/lumen2,darkestkhan/lumen
1776a2a2f02ba89ef3eaf918ad1fc34713eb579e
src/security-auth-oauth.ads
src/security-auth-oauth.ads
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- 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); -- 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); -- 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; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- 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); -- 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); -- 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; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; Issuer : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
Add the issuer initialize from the configuration parameters
Add the issuer initialize from the configuration parameters
Ada
apache-2.0
Letractively/ada-security
dafb593ad50d57e4cecf63e98411a6d768f4199c
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Servlets.Faces; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the new AWA.Modules unit test
Add the new AWA.Modules unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
eb47a2a811e12630a11dd1f0722184ba573b2251
samples/functions.adb
samples/functions.adb
----------------------------------------------------------------------- -- functions -- Show how to plug and use functions -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with EL.Functions.Default; with Ada.Text_IO; with Bean; procedure Functions is use Bean; use Ada.Text_IO; use EL.Expressions; use EL.Objects; E : Expression; Fn : constant EL.Functions.Function_Mapper_Access := new EL.Functions.Default.Default_Function_Mapper; Ctx : EL.Contexts.Default.Default_Context; Joe : constant Person_Access := Create_Person ("Joe", "Smith", 12); Bill : constant Person_Access := Create_Person ("Bill", "Johnson", 42); Result : Object; begin -- Register the 'format' function. Fn.Set_Function (Namespace => "", Name => "format", Func => Bean.Format'Access); Ctx.Set_Function_Mapper (Fn); -- Create the expression E := Create_Expression ("#{format(user.firstName) & ' ' & user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Put_Line ("Joe's name is " & To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Put_Line ("Bill's name is " & To_String (Result)); end Functions;
----------------------------------------------------------------------- -- functions -- Show how to plug and use functions -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with EL.Functions.Default; with Ada.Text_IO; with Bean; procedure Functions is use Bean; use Ada.Text_IO; use EL.Expressions; use EL.Objects; E : Expression; Fn : constant EL.Functions.Function_Mapper_Access := new EL.Functions.Default.Default_Function_Mapper; Ctx : EL.Contexts.Default.Default_Context; Joe : constant Person_Access := Create_Person ("Joe", "Smith", 12); Bill : constant Person_Access := Create_Person ("Bill", "Johnson", 42); Result : Object; begin -- Register the 'format' function. Fn.Set_Function (Namespace => "", Name => "format", Func => Bean.Format'Access); Ctx.Set_Function_Mapper (Fn); -- Create the expression E := Create_Expression ("#{format(user.firstName)} #{user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Put_Line ("Joe's name is " & To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Put_Line ("Bill's name is " & To_String (Result)); end Functions;
Update the EL expression (both variants work but this later implementation is more conformed to the JSR specification)
Update the EL expression (both variants work but this later implementation is more conformed to the JSR specification)
Ada
apache-2.0
stcarrez/ada-el
02d381c2b792fdedd29c60e3afbc64e9a682242b
src/util-serialize-io-json.ads
src/util-serialize-io-json.ads
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; end record; type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; end record; type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
Declare the Write_Enum_Entity for enum image value serialization
Declare the Write_Enum_Entity for enum image value serialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0cab0f999fa3ee35cdd0285e67e83a5f62c7d5de
src/util-serialize-io-json.ads
src/util-serialize-io-json.ads
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
Declare the Write_Field_Name function
Declare the Write_Field_Name function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4db986f7c027bfdbff5623cd5eb9922b6bc63de4
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, 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; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- 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; function Encode (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- 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 Decoder; Data : in String) return String; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- 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 array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- 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> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array 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; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) 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 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; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is new Ada.Finalization.Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); 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; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- 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; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- 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 Decoder; Data : in String) return String; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- 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 array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- 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> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array 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; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) 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 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; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- 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; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is new Ada.Finalization.Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
Declare Decode_Binary function Rename Decode into Decode_Binary to avoid call issues due to different types Declare a Transform function that returns a binary data
Declare Decode_Binary function Rename Decode into Decode_Binary to avoid call issues due to different types Declare a Transform function that returns a binary data
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ca274f645b5589f8bd8886ed1524391f12fe2f55
awa/plugins/awa-comments/src/model/awa-comments-models.ads
awa/plugins/awa-comments/src/model/awa-comments-models.ads
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On, "unit * is not referenced"); package AWA.Comments.Models is -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return Status_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Readonly_Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the given name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the value identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comments"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 8, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access ) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with others => <>); type Comment_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : Status_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "23485D2C3F50D233CB8D52A2414B417F4296B51A"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; end AWA.Comments.Models;
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On, "unit * is not referenced"); package AWA.Comments.Models is -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return Status_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Readonly_Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the given name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the value identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comment"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 8, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access ) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with others => <>); type Comment_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : Status_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "23485D2C3F50D233CB8D52A2414B417F4296B51A"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; end AWA.Comments.Models;
Rebuild the model files (rename table awa_comment)
Rebuild the model files (rename table awa_comment)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
308605a44acb6b38a88a3906350594304bc15b14
awa/regtests/awa-events-services-tests.adb
awa/regtests/awa-events-services-tests.adb
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Methods; with Util.Log.Loggers; with Util.Measures; with Util.Concurrent.Counters; with EL.Beans; with EL.Expressions; with EL.Contexts.Default; with ASF.Applications; with ASF.Servlets.Faces; with AWA.Applications; with AWA.Applications.Configs; with AWA.Applications.Factory; with AWA.Events.Action_Method; with AWA.Services.Contexts; with AWA.Events.Queues; with AWA.Events.Services; package body AWA.Events.Services.Tests is use AWA.Events.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests"); package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name", Test_Get_Event_Name'Access); Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous", Test_Dispatch_Synchronous'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo", Test_Dispatch_Fifo'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist", Test_Dispatch_Persist'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn", Test_Dispatch_Synchronous_Dyn'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise", Test_Dispatch_Synchronous_Raise'Access); end Add_Tests; type Action_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Count : Natural := 0; Priority : Integer := 0; Raise_Exception : Boolean := False; end record; type Action_Bean_Access is access all Action_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Action_Bean, Method => Event_Action, Name => "send"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "priority" then From.Priority := Util.Beans.Objects.To_Integer (Value); elsif Name = "raise_exception" then From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value); end if; end Set_Value; overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; Action_Exception : exception; Global_Counter : Util.Concurrent.Counters.Counter; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); begin if From.Raise_Exception then raise Action_Exception with "Raising an exception from the event action bean"; end if; From.Count := From.Count + 1; Util.Concurrent.Counters.Increment (Global_Counter); end Event_Action; function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Action_Bean_Access := new Action_Bean; begin return Result.all'Access; end Create_Action_Bean; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test the Get_Event_Type_Name internal operation. -- ------------------------------ procedure Test_Get_Event_Name (T : in out Test) is begin Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all, "Get_Event_Type_Name"); end Test_Get_Event_Name; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; begin Manager.Initialize (App.all'Access); T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Action : constant EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Queue : Queue_Ref; Index : constant Event_Index := Find_Event_Index ("event-test-4"); begin Manager.Initialize (App.all'Access); Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx); Manager.Add_Queue (Queue); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => Queue, Action => Action, Params => Props); Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length), "Add_Action failed"); end loop; end Test_Add_Action; -- ------------------------------ -- Test dispatching events -- ------------------------------ procedure Dispatch_Event (T : in out Test; Kind : in Event_Index; Expect_Count : in Natural; Expect_Prio : in Natural) is Factory : AWA.Applications.Factory.Application_Factory; Conf : ASF.Applications.Config; Ctx : aliased EL.Contexts.Default.Default_Context; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml"); Action : aliased Action_Bean; begin Conf.Set ("database", Util.Tests.Get_Parameter ("database")); declare App : aliased AWA.Tests.Test_Application; S : Util.Measures.Stamp; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; SC : AWA.Services.Contexts.Service_Context; begin App.Initialize (Conf => Conf, Factory => Factory); App.Set_Global ("event_test", Util.Beans.Objects.To_Object (Action'Unchecked_Access, Util.Beans.Objects.STATIC)); SC.Set_Context (App'Unchecked_Access, null); App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Register_Class ("AWA.Events.Tests.Event_Action", Create_Action_Bean'Access); AWA.Applications.Configs.Read_Configuration (App => App, File => Path, Context => Ctx'Unchecked_Access); Util.Measures.Report (S, "Initialize AWA application and read config"); App.Start; Util.Measures.Report (S, "Start event tasks"); for I in 1 .. 100 loop declare Event : Module_Event; begin Event.Set_Event_Kind (Kind); Event.Set_Parameter ("prio", "3"); Event.Set_Parameter ("template", "def"); App.Send_Event (Event); end; end loop; Util.Measures.Report (S, "Send 100 events"); end; Log.Info ("Action count: {0}", Natural'Image (Action.Count)); Log.Info ("Priority: {0}", Integer'Image (Action.Priority)); Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority, "prio parameter not transmitted (global bean)"); Util.Tests.Assert_Equals (T, Expect_Count, Action.Count, "invalid number of calls for the action (global bean)"); end Dispatch_Event; -- ------------------------------ -- Test dispatching synchronous event to a global bean. -- ------------------------------ procedure Test_Dispatch_Synchronous (T : in out Test) is begin T.Dispatch_Event (Event_Test_1.Kind, 500, 3); end Test_Dispatch_Synchronous; -- ------------------------------ -- Test dispatching event through a fifo queue. -- ------------------------------ procedure Test_Dispatch_Fifo (T : in out Test) is begin T.Dispatch_Event (Event_Test_2.Kind, 200, 3); end Test_Dispatch_Fifo; -- ------------------------------ -- Test dispatching event through a database queue. -- ------------------------------ procedure Test_Dispatch_Persist (T : in out Test) is begin T.Dispatch_Event (Event_Test_5.Kind, 100, 3); end Test_Dispatch_Persist; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean (created on demand). -- ------------------------------ procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is begin T.Dispatch_Event (Event_Test_3.Kind, 0, 0); end Test_Dispatch_Synchronous_Dyn; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean and raise an exception in the action. -- ------------------------------ procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is begin T.Dispatch_Event (Event_Test_4.Kind, 0, 0); end Test_Dispatch_Synchronous_Raise; end AWA.Events.Services.Tests;
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Methods; with Util.Log.Loggers; with Util.Measures; with Util.Concurrent.Counters; with EL.Beans; with EL.Expressions; with EL.Contexts.Default; with ASF.Applications; with ASF.Servlets.Faces; with AWA.Applications; with AWA.Applications.Configs; with AWA.Applications.Factory; with AWA.Events.Action_Method; with AWA.Services.Contexts; with AWA.Events.Queues; with AWA.Events.Services; package body AWA.Events.Services.Tests is use AWA.Events.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests"); package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name", Test_Get_Event_Name'Access); Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous", Test_Dispatch_Synchronous'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo", Test_Dispatch_Fifo'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist", Test_Dispatch_Persist'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn", Test_Dispatch_Synchronous_Dyn'Access); Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise", Test_Dispatch_Synchronous_Raise'Access); end Add_Tests; type Action_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Count : Natural := 0; Priority : Integer := 0; Raise_Exception : Boolean := False; end record; type Action_Bean_Access is access all Action_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Action_Bean, Method => Event_Action, Name => "send"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Action_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Action_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "priority" then From.Priority := Util.Beans.Objects.To_Integer (Value); elsif Name = "raise_exception" then From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value); end if; end Set_Value; overriding function Get_Method_Bindings (From : in Action_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; Action_Exception : exception; Global_Counter : Util.Concurrent.Counters.Counter; procedure Event_Action (From : in out Action_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); begin if From.Raise_Exception then raise Action_Exception with "Raising an exception from the event action bean"; end if; From.Count := From.Count + 1; Util.Concurrent.Counters.Increment (Global_Counter); end Event_Action; function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Action_Bean_Access := new Action_Bean; begin return Result.all'Access; end Create_Action_Bean; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test the Get_Event_Type_Name internal operation. -- ------------------------------ procedure Test_Get_Event_Name (T : in out Test) is begin Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all, "Get_Event_Type_Name"); Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all, "Get_Event_Type_Name"); end Test_Get_Event_Name; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; begin Manager.Initialize (App.all'Access); T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Action : constant EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Queue : Queue_Ref; Index : constant Event_Index := Find_Event_Index ("event-test-4"); begin Manager.Initialize (App.all'Access); Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx); Manager.Add_Queue (Queue); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => Queue, Action => Action, Params => Props); Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length), "Add_Action failed"); end loop; end Test_Add_Action; -- ------------------------------ -- Test dispatching events -- ------------------------------ procedure Dispatch_Event (T : in out Test; Kind : in Event_Index; Expect_Count : in Natural; Expect_Prio : in Natural) is Factory : AWA.Applications.Factory.Application_Factory; Conf : ASF.Applications.Config; Ctx : aliased EL.Contexts.Default.Default_Context; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml"); Action : aliased Action_Bean; begin Conf.Set ("database", Util.Tests.Get_Parameter ("database")); declare App : aliased AWA.Tests.Test_Application; S : Util.Measures.Stamp; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; SC : AWA.Services.Contexts.Service_Context; begin App.Initialize (Conf => Conf, Factory => Factory); App.Set_Global ("event_test", Util.Beans.Objects.To_Object (Action'Unchecked_Access, Util.Beans.Objects.STATIC)); SC.Set_Context (App'Unchecked_Access, null); App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Register_Class ("AWA.Events.Tests.Event_Action", Create_Action_Bean'Access); AWA.Applications.Configs.Read_Configuration (App => App, File => Path, Context => Ctx'Unchecked_Access); Util.Measures.Report (S, "Initialize AWA application and read config"); App.Start; Util.Measures.Report (S, "Start event tasks"); for I in 1 .. 100 loop declare Event : Module_Event; begin Event.Set_Event_Kind (Kind); Event.Set_Parameter ("prio", "3"); Event.Set_Parameter ("template", "def"); App.Send_Event (Event); end; end loop; Util.Measures.Report (S, "Send 100 events"); -- Wait for the dispatcher to process the events but do not wait more than 10 secs. for I in 1 .. 10_000 loop exit when Action.Count = Expect_Count; delay 0.1; end loop; end; Log.Info ("Action count: {0}", Natural'Image (Action.Count)); Log.Info ("Priority: {0}", Integer'Image (Action.Priority)); Util.Tests.Assert_Equals (T, Expect_Count, Action.Count, "invalid number of calls for the action (global bean)"); Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority, "prio parameter not transmitted (global bean)"); end Dispatch_Event; -- ------------------------------ -- Test dispatching synchronous event to a global bean. -- ------------------------------ procedure Test_Dispatch_Synchronous (T : in out Test) is begin T.Dispatch_Event (Event_Test_1.Kind, 500, 3); end Test_Dispatch_Synchronous; -- ------------------------------ -- Test dispatching event through a fifo queue. -- ------------------------------ procedure Test_Dispatch_Fifo (T : in out Test) is begin T.Dispatch_Event (Event_Test_2.Kind, 200, 3); end Test_Dispatch_Fifo; -- ------------------------------ -- Test dispatching event through a database queue. -- ------------------------------ procedure Test_Dispatch_Persist (T : in out Test) is begin T.Dispatch_Event (Event_Test_5.Kind, 100, 3); end Test_Dispatch_Persist; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean (created on demand). -- ------------------------------ procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is begin T.Dispatch_Event (Event_Test_3.Kind, 0, 0); end Test_Dispatch_Synchronous_Dyn; -- ------------------------------ -- Test dispatching synchronous event to a dynamic bean and raise an exception in the action. -- ------------------------------ procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is begin T.Dispatch_Event (Event_Test_4.Kind, 0, 0); end Test_Dispatch_Synchronous_Raise; end AWA.Events.Services.Tests;
Fix random failures that could happen because we check for the action result too quickly. Wait for the events to have been dispatched.
Fix random failures that could happen because we check for the action result too quickly. Wait for the events to have been dispatched.
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
4de9a22a9d1735d73636699a1435ba3254e5678d
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Permissions; with AWA.Modules; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Permissions; with ADO; with AWA.Modules; with AWA.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Declare Save_Wiki_Space and Load_Wiki_Space procedures
Declare Save_Wiki_Space and Load_Wiki_Space procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ed1a7378fd9efa978902a9d50a011feb83b5b7bf
src/asf-components-html-messages.adb
src/asf-components-html-messages.adb
----------------------------------------------------------------------- -- html.messages -- Faces messages -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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, False); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, True); 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, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.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, False); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, True); 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;
Add quotes arround component name in error message to better identify the component name from the message itself
Add quotes arround component name in error message to better identify the component name from the message itself
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
5b088cc8ea6ee1f3c340c4a23bdae43ce8fb17b0
src/gen-model-xmi.ads
src/gen-model-xmi.ads
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Data_Type_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
Make the enumeration a data type
Make the enumeration a data type
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
6916f211487f42d2c09ac4be2eabde31e0d595c6
src/babel-strategies.adb
src/babel-strategies.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Instance (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- Set the buffer pool to be used by Allocate_Buffer. -- ------------------------------ procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; procedure Print_Sha (File : in Babel.Files.File_Type) is Sha : constant String := Babel.Files.Get_SHA1 (File); begin Log.Info (Babel.Files.Get_Path (File) & " => " & Sha); end Print_Sha; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Print_Sha (File); Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. -- ------------------------------ procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- Set the file filters that will be used when scanning the read store. -- ------------------------------ procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- Set the read and write stores that the strategy will use. -- ------------------------------ procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin Strategy.Database := Database; end Set_Database; end Babel.Strategies;
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Buffer (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Babel.Files.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- Set the buffer pool to be used by Allocate_Buffer. -- ------------------------------ procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. -- ------------------------------ procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- Set the file filters that will be used when scanning the read store. -- ------------------------------ procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- Set the read and write stores that the strategy will use. -- ------------------------------ procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin Strategy.Database := Database; end Set_Database; end Babel.Strategies;
Fix compilation after changes in Babel.Files.Buffers
Fix compilation after changes in Babel.Files.Buffers
Ada
apache-2.0
stcarrez/babel
bac917989bda4bbe76f7274eefa2559c2f511793
regtests/util-properties-tests.adb
regtests/util-properties-tests.adb
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.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"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); 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; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_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); T.Assert (Copy.Exists ("prefix.one"), "Property one not found"); T.Assert (Copy.Exists ("prefix.two"), "Property two not found"); T.Assert (Copy.Exists ("prefix"), "Property '' does not exist."); T.Assert (Copy.Exists ("prefix."), "Property '' does not exist."); end; 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; 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"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; 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; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; 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; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); 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; declare V : Util.Properties.Value; P : Properties.Manager with Unreferenced; begin P := Util.Properties.To_Manager (V); T.Fail ("No exception raised by To_Manager"); exception when Util.Beans.Objects.Conversion_Error => null; end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_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.Remove", Test_Remove_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); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.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"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); 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; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_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); T.Assert (Copy.Exists ("prefix.one"), "Property one not found"); T.Assert (Copy.Exists ("prefix.two"), "Property two not found"); T.Assert (Copy.Exists ("prefix"), "Property '' does not exist."); T.Assert (Copy.Exists ("prefix."), "Property '' does not exist."); end; 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 for Pass in 1 .. 2 loop 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; 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"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; 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; Props.Set ("c", "d"); end loop; 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; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; 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; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); 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; declare V : Util.Properties.Value; P : Properties.Manager with Unreferenced; begin P := Util.Properties.To_Manager (V); T.Fail ("No exception raised by To_Manager"); exception when Util.Beans.Objects.Conversion_Error => null; end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_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.Remove", Test_Remove_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); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
Fix the Test_Missing_Property unit test to check the operation on a non-empty property set
Fix the Test_Missing_Property unit test to check the operation on a non-empty property set
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fc8b2c614aef5014d40c374da6b751c4c35132e7
src/sys/os-win32/util-systems-constants.ads
src/sys/os-win32/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#000400#; O_EXCL : constant Interfaces.C.int := 8#002000#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#000010#; O_CLOEXEC : constant Interfaces.C.int := 0; O_SYNC : constant Interfaces.C.int := 0; O_DIRECT : constant Interfaces.C.int := 0; DLL_OPTIONS : constant String := ""; SYMBOL_PREFIX : constant String := ""; 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#000400#; O_EXCL : constant Interfaces.C.int := 8#002000#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#000010#; O_CLOEXEC : constant Interfaces.C.int := 8#100000#; O_SYNC : constant Interfaces.C.int := 0; O_DIRECT : constant Interfaces.C.int := 0; DLL_OPTIONS : constant String := ""; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
Fix definition of O_CLOEXEC
Fix definition of O_CLOEXEC
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
79243abc31b60adeeaeb853bb01a5c505c34beaa
src/drivers/adabase-driver-base-sqlite.adb
src/drivers/adabase-driver-base-sqlite.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.SQLite is ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out SQLite_Driver) is msg : constant CT.Text := CT.SUS ("Disconnect From " & CT.USS (driver.database) & "database"); err : constant CT.Text := CT.SUS ("ACK! Disconnect attempted on inactive connection"); begin if driver.connection_active then driver.connection.disconnect; driver.connection_active := False; driver.log_nominal (category => disconnecting, message => msg); else -- Non-fatal attempt to disconnect db when none is connected driver.log_problem (category => disconnecting, message => err); end if; end disconnect; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : SQLite_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Rollback attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Rollback attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Rollback attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to roll back when no database is connected driver.log_problem (category => miscellaneous, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to roll back when autocommit is on driver.log_problem (category => miscellaneous, message => err2); return; end if; driver.connection.rollback; exception when ACS.ROLLBACK_FAIL => driver.log_problem (category => miscellaneous, message => err3, pull_codes => True); end rollback; -------------- -- commit -- -------------- overriding procedure commit (driver : SQLite_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Commit attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Commit attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Commit attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to commit when no database is connected driver.log_problem (category => transaction, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to commit when autocommit is on driver.log_problem (category => transaction, message => err2); return; end if; driver.connection.all.commit; exception when ACS.COMMIT_FAIL => driver.log_problem (category => transaction, message => err3, pull_codes => True); end commit; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : SQLite_Driver) return TraxID is begin return driver.connection.all.lastInsertID; end last_insert_id; ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : SQLite_Driver) return TSqlState is begin return driver.connection.all.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : SQLite_Driver) return DriverCodes is begin return driver.connection.all.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : SQLite_Driver) return String is begin return driver.connection.all.driverMessage; end last_driver_message; --------------- -- execute -- --------------- overriding function execute (driver : SQLite_Driver; sql : String) return AffectedRows is result : AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); begin if driver.connection_active then driver.connection.all.execute (sql => sql); result := driver.connection.all.rows_affected_by_execution; driver.log_nominal (category => execution, message => CT.SUS (sql)); else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return result; exception when ACS.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return 0; end execute; ------------------------------------------------------------------------ -- ROUTINES OF ALL DRIVERS NOT COVERED BY INTERFACES (TECH REASON) -- ------------------------------------------------------------------------ ------------- -- query -- ------------- function query (driver : SQLite_Driver; sql : String) return ASS.SQLite_statement is begin return driver.private_statement (sql => sql, prepared => False); end query; --------------- -- prepare -- --------------- function prepare (driver : SQLite_Driver; sql : String) return ASS.SQLite_statement is begin return driver.private_statement (sql => sql, prepared => True); end prepare; -------------------- -- query_select -- -------------------- function query_select (driver : SQLite_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : NullPriority := native; limit : TraxID := 0; offset : TraxID := 0) return ASS.SQLite_statement is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if null_sort /= native then driver.log_nominal (category => execution, message => CT.SUS ("Note that NULLS FIRST/LAST is not " & "supported by MySQL so the null_sort setting is ignored")); end if; if limit > 0 then if offset > 0 then return driver.private_statement (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img, False); else return driver.private_statement (vanilla & " LIMIT" & limit'Img, False); end if; end if; return driver.private_statement (vanilla, False); end query_select; ---------------------- -- prepare_select -- ---------------------- function prepare_select (driver : SQLite_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : NullPriority := native; limit : TraxID := 0; offset : TraxID := 0) return ASS.SQLite_statement is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if null_sort /= native then driver.log_nominal (category => execution, message => CT.SUS ("Note that NULLS FIRST/LAST is not " & "supported by MySQL so the null_sort setting is ignored")); end if; if limit > 0 then if offset > 0 then return driver.private_statement (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img, True); else return driver.private_statement (vanilla & " LIMIT" & limit'Img, True); end if; end if; return driver.private_statement (vanilla, True); end prepare_select; ------------------------------------------------------------------------ -- PUBLIC ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out SQLite_Driver; database : String; username : String := blankstring; password : String := blankstring; socket : String := blankstring) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out SQLite_Driver; database : String; username : String := blankstring; password : String := blankstring; hostname : String := blankstring; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ------------------------------------------------------------------------ -- PRIVATE ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out SQLite_Driver) is begin Object.connection := backend'Access; Object.local_connection := backend'Access; Object.dialect := driver_sqlite; end initialize; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out SQLite_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.all.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (ACS.EX.Exception_Message (X => Error))); end private_connect; ------------------------- -- private_statement -- ------------------------- function private_statement (driver : SQLite_Driver; sql : String; prepared : Boolean) return ASS.SQLite_statement is stype : AID.ASB.stmt_type := AID.ASB.direct_statement; logcat : LogCategory := execution; err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); duplicate : aliased String := sql; begin if prepared then stype := AID.ASB.prepared_statement; logcat := statement_preparation; end if; if driver.connection_active then declare statement : ASS.SQLite_statement (type_of_statement => stype, log_handler => logger'Access, sqlite_conn => driver.local_connection, initial_sql => duplicate'Unchecked_Access, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size); begin if not prepared then if statement.successful then driver.log_nominal (category => logcat, message => CT.SUS ("query succeeded," & statement.rows_returned'Img & " rows returned")); else driver.log_nominal (category => execution, message => CT.SUS ("Query failed!")); end if; end if; return statement; exception when RES : others => -- Fatal attempt to prepare a statement -- Logged already by stmt initialization -- Should be internally marked as unsuccessful return statement; end; else -- Fatal attempt to query an unconnected database driver.log_problem (category => logcat, message => err1, break => True); end if; -- We never get here, the driver.log_problem throws exception first raise ACS.STMT_NOT_VALID with "failed to return SQLite statement"; end private_statement; ------------------------ -- query_drop_table -- ------------------------ overriding procedure query_drop_table (driver : SQLite_Driver; tables : String; when_exists : Boolean := False; cascade : Boolean := False) is sql : CT.Text; AR : AffectedRows; begin if CT.contains (tables, ",") then driver.log_problem (category => execution, message => CT.SUS ("Multiple tables detected -- SQLite" & " can only drop one table at a time : " & tables)); return; end if; case when_exists is when True => sql := CT.SUS ("DROP TABLE IF EXISTS " & tables); when False => sql := CT.SUS ("DROP TABLE " & tables); end case; if cascade then driver.log_nominal (category => execution, message => CT.SUS ("Note that requested CASCADE has no effect " & "on SQLite")); end if; AR := driver.execute (sql => CT.USS (sql)); end query_drop_table; ------------------------- -- query_clear_table -- ------------------------- overriding procedure query_clear_table (driver : SQLite_Driver; table : String) is -- SQLite has no "truncate" commands sql : constant String := "DELETE FROM " & table; AR : AffectedRows; begin AR := driver.execute (sql => sql); end query_clear_table; end AdaBase.Driver.Base.SQLite;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.SQLite is ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out SQLite_Driver) is msg : constant CT.Text := CT.SUS ("Disconnect From " & CT.USS (driver.database) & "database"); err : constant CT.Text := CT.SUS ("ACK! Disconnect attempted on inactive connection"); begin if driver.connection_active then driver.connection.disconnect; driver.connection_active := False; driver.log_nominal (category => disconnecting, message => msg); else -- Non-fatal attempt to disconnect db when none is connected driver.log_problem (category => disconnecting, message => err); end if; end disconnect; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : SQLite_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Rollback attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Rollback attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Rollback attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to roll back when no database is connected driver.log_problem (category => miscellaneous, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to roll back when autocommit is on driver.log_problem (category => miscellaneous, message => err2); return; end if; driver.connection.rollback; exception when ACS.ROLLBACK_FAIL => driver.log_problem (category => miscellaneous, message => err3, pull_codes => True); end rollback; -------------- -- commit -- -------------- overriding procedure commit (driver : SQLite_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Commit attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Commit attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Commit attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to commit when no database is connected driver.log_problem (category => transaction, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to commit when autocommit is on driver.log_problem (category => transaction, message => err2); return; end if; driver.connection.all.commit; exception when ACS.COMMIT_FAIL => driver.log_problem (category => transaction, message => err3, pull_codes => True); end commit; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : SQLite_Driver) return TraxID is begin return driver.connection.all.lastInsertID; end last_insert_id; ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : SQLite_Driver) return TSqlState is begin return driver.connection.all.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : SQLite_Driver) return DriverCodes is begin return driver.connection.all.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : SQLite_Driver) return String is begin return driver.connection.all.driverMessage; end last_driver_message; --------------- -- execute -- --------------- overriding function execute (driver : SQLite_Driver; sql : String) return AffectedRows is result : AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); begin if driver.connection_active then driver.connection.all.execute (sql => sql); result := driver.connection.all.rows_affected_by_execution; driver.log_nominal (category => execution, message => CT.SUS (sql)); else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return result; exception when ACS.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return 0; end execute; ------------------------------------------------------------------------ -- ROUTINES OF ALL DRIVERS NOT COVERED BY INTERFACES (TECH REASON) -- ------------------------------------------------------------------------ ------------- -- query -- ------------- function query (driver : SQLite_Driver; sql : String) return ASS.SQLite_statement is begin return driver.private_statement (sql => sql, prepared => False); end query; --------------- -- prepare -- --------------- function prepare (driver : SQLite_Driver; sql : String) return ASS.SQLite_statement is begin return driver.private_statement (sql => sql, prepared => True); end prepare; -------------------- -- query_select -- -------------------- function query_select (driver : SQLite_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : NullPriority := native; limit : TraxID := 0; offset : TraxID := 0) return ASS.SQLite_statement is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if null_sort /= native then driver.log_nominal (category => execution, message => CT.SUS ("Note that NULLS FIRST/LAST is not " & "supported by MySQL so the null_sort setting is ignored")); end if; if limit > 0 then if offset > 0 then return driver.private_statement (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img, False); else return driver.private_statement (vanilla & " LIMIT" & limit'Img, False); end if; end if; return driver.private_statement (vanilla, False); end query_select; ---------------------- -- prepare_select -- ---------------------- function prepare_select (driver : SQLite_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : NullPriority := native; limit : TraxID := 0; offset : TraxID := 0) return ASS.SQLite_statement is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if null_sort /= native then driver.log_nominal (category => execution, message => CT.SUS ("Note that NULLS FIRST/LAST is not " & "supported by MySQL so the null_sort setting is ignored")); end if; if limit > 0 then if offset > 0 then return driver.private_statement (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img, True); else return driver.private_statement (vanilla & " LIMIT" & limit'Img, True); end if; end if; return driver.private_statement (vanilla, True); end prepare_select; ------------------------------------------------------------------------ -- PUBLIC ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out SQLite_Driver; database : String; username : String := blankstring; password : String := blankstring; socket : String := blankstring) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out SQLite_Driver; database : String; username : String := blankstring; password : String := blankstring; hostname : String := blankstring; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ------------------------------------------------------------------------ -- PRIVATE ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out SQLite_Driver) is begin Object.connection := backend'Access; Object.local_connection := backend'Access; Object.dialect := driver_sqlite; end initialize; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out SQLite_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.all.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (ACS.EX.Exception_Message (X => Error))); end private_connect; ------------------------- -- private_statement -- ------------------------- function private_statement (driver : SQLite_Driver; sql : String; prepared : Boolean) return ASS.SQLite_statement is stype : AID.ASB.stmt_type := AID.ASB.direct_statement; logcat : LogCategory := execution; err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); duplicate : aliased String := sql; begin if prepared then stype := AID.ASB.prepared_statement; logcat := statement_preparation; end if; if driver.connection_active then declare statement : ASS.SQLite_statement (type_of_statement => stype, log_handler => logger'Access, sqlite_conn => driver.local_connection, initial_sql => duplicate'Unchecked_Access, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size); begin if not prepared then if statement.successful then driver.log_nominal (category => logcat, message => CT.SUS ("query succeeded," & statement.rows_returned'Img & " rows returned")); else driver.log_nominal (category => execution, message => CT.SUS ("Query failed!")); end if; end if; return statement; exception when RES : others => -- Fatal attempt to prepare a statement -- Logged already by stmt initialization -- Should be internally marked as unsuccessful return statement; end; else -- Fatal attempt to query an unconnected database driver.log_problem (category => logcat, message => err1, break => True); end if; -- We never get here, the driver.log_problem throws exception first raise ACS.STMT_NOT_VALID with "failed to return SQLite statement"; end private_statement; ------------------------ -- query_drop_table -- ------------------------ overriding procedure query_drop_table (driver : SQLite_Driver; tables : String; when_exists : Boolean := False; cascade : Boolean := False) is sql : CT.Text; AR : AffectedRows; begin if CT.contains (tables, ",") then driver.log_problem (category => execution, message => CT.SUS ("Multiple tables detected -- SQLite" & " can only drop one table at a time : " & tables)); return; end if; case when_exists is when True => sql := CT.SUS ("DROP TABLE IF EXISTS " & tables); when False => sql := CT.SUS ("DROP TABLE " & tables); end case; if cascade then driver.log_nominal (category => note, message => CT.SUS ("Requested CASCADE has no effect on SQLite")); end if; AR := driver.execute (sql => CT.USS (sql)); end query_drop_table; ------------------------- -- query_clear_table -- ------------------------- overriding procedure query_clear_table (driver : SQLite_Driver; table : String) is -- SQLite has no "truncate" commands sql : constant String := "DELETE FROM " & table; AR : AffectedRows; begin AR := driver.execute (sql => sql); end query_clear_table; end AdaBase.Driver.Base.SQLite;
Tweak SQLite cascade message to match MySQL
Tweak SQLite cascade message to match MySQL
Ada
isc
jrmarino/AdaBase
781c8552d4234947059005b3c1046b171cf3c6ed
samples/wget.adb
samples/wget.adb
----------------------------------------------------------------------- -- wget -- A simple wget command to fetch a page -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Http.Clients; with Util.Http.Clients.Curl; procedure Wget is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: wget url ..."); Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com"); return; end if; Util.Http.Clients.Curl.Register; for I in 1 .. Count loop declare Http : Util.Http.Clients.Client; URI : constant String := Ada.Command_Line.Argument (1); Response : Util.Http.Clients.Response; begin Http.Add_Header ("X-Requested-By", "wget"); Http.Get (URI, Response); Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status)); Ada.Text_IO.Put_Line (Response.Get_Body); end; end loop; end Wget;
----------------------------------------------------------------------- -- wget -- A simple wget command to fetch a page -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Http.Clients; with Util.Http.Clients.Curl; procedure Wget is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: wget url ..."); Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com"); return; end if; Util.Http.Clients.Curl.Register; for I in 1 .. Count loop declare Http : Util.Http.Clients.Client; URI : constant String := Ada.Command_Line.Argument (I); Response : Util.Http.Clients.Response; begin Http.Add_Header ("X-Requested-By", "wget"); Http.Get (URI, Response); Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status)); Ada.Text_IO.Put_Line (Response.Get_Body); end; end loop; end Wget;
Fix wget loop over argument list
Fix wget loop over argument list Using the letter I variable name may be unfortunate as it resembles the number 1. Loop over all command line arguments instead of repeating the first argument.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6899ea6567ce7e23783f4dec818a254235bbf6e9
awa/plugins/awa-settings/src/awa-settings.adb
awa/plugins/awa-settings/src/awa-settings.adb
----------------------------------------------------------------------- -- awa-settings -- Settings 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.Strings.Unbounded; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is begin return Default; end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
----------------------------------------------------------------------- -- awa-settings -- Settings 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.Strings.Unbounded; with Util.Strings; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is begin return Default; end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6fbc49ef932bec6dad0c86fcdee2c0cba3c4003b
src/util-concurrent-fifos.ads
src/util-concurrent-fifos.ads
----------------------------------------------------------------------- -- Util.Concurrent.Fifos -- Concurrent Fifo Queues -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Fifos</b> generic defines a queue of objects which -- can be shared by multiple threads. First, the queue size is configured -- by using the <b>Set_Size</b> procedure. Then, a thread can insert elements -- in the queue by using the <b>Enqueue</b> procedure. The thread will block -- if the queue is full. Another thread can use the <b>Dequeue</b> procedure -- to fetch the oldest element from the queue. The thread will block -- until an element is inserted if the queue is empty. generic type Element_Type is private; -- The default queue size. Default_Size : in Positive; -- After a dequeue, clear the element stored in the queue. Clear_On_Dequeue : in Boolean := False; package Util.Concurrent.Fifos is FOREVER : constant Duration := -1.0; -- Exception raised if the enqueue or dequeue timeout exceeded. Timeout : exception; -- Fifo of objects type Fifo is new Ada.Finalization.Limited_Controlled with private; -- Put the element in the queue. procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER); -- Get an element from the queue. -- Wait until one element gets available. procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER); -- Get the number of elements in the queue. function Get_Count (From : in Fifo) return Natural; -- Set the queue size. procedure Set_Size (Into : in out Fifo; Capacity : in Positive); -- Initializes the queue. overriding procedure Initialize (Object : in out Fifo); -- Release the queue elements. overriding procedure Finalize (Object : in out Fifo); private -- To store the queue elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Natural range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Queue of objects. protected type Protected_Fifo is -- Put the element in the queue. -- If the queue is full, wait until some room is available. entry Enqueue (Item : in Element_Type); -- Get an element from the queue. -- Wait until one element gets available. entry Dequeue (Item : out Element_Type); -- Get the number of elements in the queue. function Get_Count return Natural; -- Set the queue size. procedure Set_Size (Capacity : in Natural); private First : Positive := 1; Last : Positive := 1; Count : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Fifo; type Fifo is new Ada.Finalization.Limited_Controlled with record Buffer : Protected_Fifo; end record; end Util.Concurrent.Fifos;
----------------------------------------------------------------------- -- util-concurrent-fifos -- Concurrent Fifo Queues -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Fifos</b> generic defines a queue of objects which -- can be shared by multiple threads. First, the queue size is configured -- by using the <b>Set_Size</b> procedure. Then, a thread can insert elements -- in the queue by using the <b>Enqueue</b> procedure. The thread will block -- if the queue is full. Another thread can use the <b>Dequeue</b> procedure -- to fetch the oldest element from the queue. The thread will block -- until an element is inserted if the queue is empty. generic type Element_Type is private; -- The default queue size. Default_Size : in Positive; -- After a dequeue, clear the element stored in the queue. Clear_On_Dequeue : in Boolean := False; package Util.Concurrent.Fifos is FOREVER : constant Duration := -1.0; -- Exception raised if the enqueue or dequeue timeout exceeded. Timeout : exception; -- Fifo of objects type Fifo is new Ada.Finalization.Limited_Controlled with private; -- Put the element in the queue. procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER); -- Get an element from the queue. -- Wait until one element gets available. procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER); -- Get the number of elements in the queue. function Get_Count (From : in Fifo) return Natural; -- Set the queue size. procedure Set_Size (Into : in out Fifo; Capacity : in Positive); -- Initializes the queue. overriding procedure Initialize (Object : in out Fifo); -- Release the queue elements. overriding procedure Finalize (Object : in out Fifo); private -- To store the queue elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Natural range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Queue of objects. protected type Protected_Fifo is -- Put the element in the queue. -- If the queue is full, wait until some room is available. entry Enqueue (Item : in Element_Type); -- Get an element from the queue. -- Wait until one element gets available. entry Dequeue (Item : out Element_Type); -- Get the number of elements in the queue. function Get_Count return Natural; -- Set the queue size. procedure Set_Size (Capacity : in Natural); private First : Positive := 1; Last : Positive := 1; Count : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Fifo; type Fifo is new Ada.Finalization.Limited_Controlled with record Buffer : Protected_Fifo; end record; end Util.Concurrent.Fifos;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
07951806e0538d5c80e69f56c50f950066fc1d65
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Preformat_Start, Preformat_End, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; Invert_Header_Level : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Add a link separator
Add a link separator
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9de72a40b0df00a2a5effd3af383aebe713f6a15
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "]"); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is 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; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; 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; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin -- Memory.Manager := Memory_Probe.all'Access; Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "]"); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is 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; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; 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; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Update to use the Probe_Manager
Update to use the Probe_Manager
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fc9a583f90ab23f1e714f028f326793bf764109b
tools/druss-commands-ping.adb
tools/druss-commands-ping.adb
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with Util.Log.Loggers; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping"); -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Id : constant String := Manager.Get (Name & ".id", ""); begin -- if Manager.Get (Name & ".active", "") = "0" then -- return; -- end if; Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", "")); Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.IP)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Ping (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping {active | inactive}"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with Util.Log.Loggers; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping"); -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String); Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Id : constant String := Manager.Get (Name & ".id", ""); 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; Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", "")); Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.Ip)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin 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_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_Ping (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_Ping (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, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Ask the Bbox to ping the devices. By default it will ping"); Console.Notice (N_HELP, " all the devices that have been discovered by the Bbox."); Console.Notice (N_HELP, " The command will wait 5 seconds and it will list the active"); Console.Notice (N_HELP, " devices with their ping performance."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all Ping all the devices"); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
Add a device selector to the Do_Ping procedure Send the ping command to all, active or inactive devices Add the 'active', 'inactive' and 'all' options
Add a device selector to the Do_Ping procedure Send the ping command to all, active or inactive devices Add the 'active', 'inactive' and 'all' options
Ada
apache-2.0
stcarrez/bbox-ada-api
56e4881b761a797d561d81853afb8afbdf4a24a2
matp/src/mat-consoles.ads
matp/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_LEVEL, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_NEXT, F_PREVIOUS, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_LEVEL, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_NEXT, F_PREVIOUS, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Declare the Get_Field_Count function
Declare the Get_Field_Count function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
68b29fe020143bba03742202735b236c286b9339
awa/samples/src/atlas-applications.adb
awa/samples/src/atlas-applications.adb
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with GNAT.MD5; with Util.Log.Loggers; with Util.Properties; with Util.Beans.Basic; with Util.Strings.Transforms; with EL.Functions; with ASF.Applications; with ASF.Applications.Main; with ADO.Queries; with ADO.Sessions; with AWA.Applications.Factory; with AWA.Services.Contexts; with Atlas.Applications.Models; -- with Atlas.XXX.Module; package body Atlas.Applications is package ASC renames AWA.Services.Contexts; use AWA.Applications; type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas"); procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Create the user statistics bean which indicates what feature the user has used. -- ------------------------------ function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; Result : User_Stat_Info_Access; begin if Ctx /= null then declare List : Atlas.Applications.Models.User_Stat_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); User : constant ADO.Identifier := Ctx.Get_User_Identifier; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Applications.Models.Query_User_Stat); Query.Bind_Param ("user_id", User); Atlas.Applications.Models.List (List, Session, Query); Result := new Atlas.Applications.Models.User_Stat_Info; Result.all := List.List.Element (0); end; else Result := new Atlas.Applications.Models.User_Stat_Info; Result.Post_Count := 0; Result.Document_Count := 0; Result.Question_Count := 0; Result.Answer_Count := 0; end if; return Result.all'Access; end Create_User_Stat_Bean; -- ------------------------------ -- 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 is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- 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 is Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email)); begin return Util.Beans.Objects.To_Object (Link); end To_Gravatar_Link; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "gravatar", Namespace => ATLAS_NS_URI, Func => To_Gravatar_Link'Access); end Set_Functions; -- ------------------------------ -- Initialize the application: -- <ul> -- <li>Register the servlets and filters. -- <li>Register the application modules. -- <li>Define the servlet and filter mappings. -- </ul> -- ------------------------------ procedure Initialize (App : in Application_Access) is Fact : AWA.Applications.Factory.Application_Factory; C : ASF.Applications.Config; begin App.Self := App; begin C.Load_Properties ("atlas.properties"); Util.Log.Loggers.Initialize (Util.Properties.Manager (C)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Fact); App.Set_Global ("contextPath", CONTEXT_PATH); end Initialize; -- ------------------------------ -- 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) is procedure Register is new ASF.Applications.Main.Register_Functions (Set_Functions); begin Register (App); AWA.Applications.Application (App).Initialize_Components; App.Add_Converter (Name => "smartDateConverter", Converter => App.Self.Rel_Date_Converter'Access); App.Add_Converter (Name => "sizeConverter", Converter => App.Self.Size_Converter'Access); App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean", Handler => Create_User_Stat_Bean'Access); end Initialize_Components; -- ------------------------------ -- 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) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access); App.Add_Servlet (Name => "files", Server => App.Self.Files'Access); App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access); App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access); App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access); App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; -- ------------------------------ -- 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) is begin Log.Info ("Initializing application modules..."); Register (App => App.Self.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => App.User_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Workspaces.Modules.NAME, URI => "workspaces", Module => App.Workspace_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Mail.Modules.NAME, URI => "mail", Module => App.Mail_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => App.Blog_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => App.Storage_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => App.Image_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => App.Vote_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => App.Tag_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => App.Question_Module'Access); Register (App => App.Self.all'Access, Name => Atlas.Microblog.Modules.NAME, URI => "microblog", Module => App.Microblog_Module'Access); end Initialize_Modules; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with GNAT.MD5; with Util.Log.Loggers; with Util.Properties; with Util.Beans.Basic; with Util.Strings.Transforms; with EL.Functions; with ASF.Applications; with ASF.Applications.Main; with ADO.Queries; with ADO.Sessions; with AWA.Applications.Factory; with AWA.Services.Contexts; with Atlas.Applications.Models; -- with Atlas.XXX.Module; package body Atlas.Applications is package ASC renames AWA.Services.Contexts; use AWA.Applications; type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas"); procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Create the user statistics bean which indicates what feature the user has used. -- ------------------------------ function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; Result : User_Stat_Info_Access; begin if Ctx /= null then declare List : Atlas.Applications.Models.User_Stat_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); User : constant ADO.Identifier := Ctx.Get_User_Identifier; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Applications.Models.Query_User_Stat); Query.Bind_Param ("user_id", User); Atlas.Applications.Models.List (List, Session, Query); Result := new Atlas.Applications.Models.User_Stat_Info; Result.all := List.List.Element (0); end; else Result := new Atlas.Applications.Models.User_Stat_Info; Result.Post_Count := 0; Result.Document_Count := 0; Result.Question_Count := 0; Result.Answer_Count := 0; end if; return Result.all'Access; end Create_User_Stat_Bean; -- ------------------------------ -- 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 is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- 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 is Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email)); begin return Util.Beans.Objects.To_Object (Link); end To_Gravatar_Link; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "gravatar", Namespace => ATLAS_NS_URI, Func => To_Gravatar_Link'Access); end Set_Functions; -- ------------------------------ -- Initialize the application: -- <ul> -- <li>Register the servlets and filters. -- <li>Register the application modules. -- <li>Define the servlet and filter mappings. -- </ul> -- ------------------------------ procedure Initialize (App : in Application_Access) is Fact : AWA.Applications.Factory.Application_Factory; C : ASF.Applications.Config; begin App.Self := App; begin C.Load_Properties ("atlas.properties"); Util.Log.Loggers.Initialize (Util.Properties.Manager (C)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Fact); App.Set_Global ("contextPath", CONTEXT_PATH); end Initialize; -- ------------------------------ -- 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) is procedure Register is new ASF.Applications.Main.Register_Functions (Set_Functions); begin Register (App); AWA.Applications.Application (App).Initialize_Components; App.Add_Converter (Name => "smartDateConverter", Converter => App.Self.Rel_Date_Converter'Access); App.Add_Converter (Name => "sizeConverter", Converter => App.Self.Size_Converter'Access); App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean", Handler => Create_User_Stat_Bean'Access); end Initialize_Components; -- ------------------------------ -- 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) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access); App.Add_Servlet (Name => "files", Server => App.Self.Files'Access); App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access); App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access); App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access); App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; -- ------------------------------ -- 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) is begin Log.Info ("Initializing application modules..."); Register (App => App.Self.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => App.User_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Workspaces.Modules.NAME, URI => "workspaces", Module => App.Workspace_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Mail.Modules.NAME, URI => "mail", Module => App.Mail_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => App.Tag_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => App.Blog_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => App.Storage_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => App.Image_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => App.Vote_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => App.Question_Module'Access); Register (App => App.Self.all'Access, Name => Atlas.Microblog.Modules.NAME, URI => "microblog", Module => App.Microblog_Module'Access); end Initialize_Modules; end Atlas.Applications;
Initialize the tags module before the blog module
Initialize the tags module before the blog module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d1a67d27ef517023502c474dd9d723283da8a1c1
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Role); M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); T.Assert (not Map (Role), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Role), "The admin role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Check several roles in Set_Roles
Check several roles in Set_Roles
Ada
apache-2.0
Letractively/ada-security
f993dc10c0225e1790fc5795277cdc93451b4d1c
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.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.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test 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 Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Permissions.Permission_Manager; Perm : Permission_Type; User : Test_Principal; begin T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Manager_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); M.Add_Role_Type (Name => "admin", Result => Admin_Perm); M.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); Admin_Perm := M.Find_Role (Role); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Disable some unit tests
Disable some unit tests
Ada
apache-2.0
Letractively/ada-security
433245d50b3bbe7af747270bb12459b32298ece3
tools/druss-gateways.ads
tools/druss-gateways.ads
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Voip information (From api/v1/voip). Voip : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
Add the VoIP information
Add the VoIP information
Ada
apache-2.0
stcarrez/bbox-ada-api
306fd607d43d7acca6410b4bf48439e3f375a372
regtests/util-events-timers-tests.ads
regtests/util-events-timers-tests.ads
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); procedure Test_Timer_Event (T : in out Test); end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); -- Test empty timers. procedure Test_Empty_Timer (T : in out Test); procedure Test_Timer_Event (T : in out Test); end Util.Events.Timers.Tests;
Declare the Test_Empty_Timer procedure
Declare the Test_Empty_Timer procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3713f13e3ffef9e7a28ea6dcd67e7b83bc8fe432
src/ado-utils-streams.adb
src/ado-utils-streams.adb
----------------------------------------------------------------------- -- ado-utils-streams -- IO stream utilities -- 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. ----------------------------------------------------------------------- package body ADO.Utils.Streams is use type Ada.Streams.Stream_Element_Offset; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Initialize the blob stream to read the content of the blob. -- ------------------------------ procedure Initialize (Stream : in out Blob_Input_Stream; Blob : in ADO.Blob_Ref) is begin Stream.Data := Blob; Stream.Pos := 1; end Initialize; -- ------------------------------ -- 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 Blob_Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Blob : constant Blob_Access := Stream.Data.Value; Avail : Offset; begin if Blob = null then Last := Into'First - 1; else Avail := Blob.Data'Last - Stream.Pos + 1; if Avail > Into'Length then Avail := Into'Length; end if; Last := Into'First + Avail - 1; if Avail > 0 then Into (Into'First .. Last) := Blob.Data (Stream.Pos .. Stream.Pos + Avail - 1); Stream.Pos := Stream.Pos + Avail; end if; end if; end Read; function Get_Blob (Stream : in Blob_Output_Stream) return Blob_Ref is Size : constant Offset := Offset (Stream.Get_Size); Buffer : constant Util.Streams.Buffered.Buffer_Access := Stream.Get_Buffer; begin return Create_Blob (Data => Buffer (Buffer'First .. Buffer'First + Size - 1)); end Get_Blob; end ADO.Utils.Streams;
----------------------------------------------------------------------- -- ado-utils-streams -- IO stream utilities -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils.Streams is use type Ada.Streams.Stream_Element_Offset; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Initialize the blob stream to read the content of the blob. -- ------------------------------ procedure Initialize (Stream : in out Blob_Input_Stream; Blob : in ADO.Blob_Ref) is begin Stream.Data := Blob; Stream.Pos := 1; end Initialize; -- ------------------------------ -- 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 Blob_Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Data.Is_Null then Last := Into'First - 1; else declare Blob : constant Blob_Accessor := Stream.Data.Value; Avail : Offset := Blob.Data'Last - Stream.Pos + 1; begin if Avail > Into'Length then Avail := Into'Length; end if; Last := Into'First + Avail - 1; if Avail > 0 then Into (Into'First .. Last) := Blob.Data (Stream.Pos .. Stream.Pos + Avail - 1); Stream.Pos := Stream.Pos + Avail; end if; end; end if; end Read; function Get_Blob (Stream : in Blob_Output_Stream) return Blob_Ref is Size : constant Offset := Offset (Stream.Get_Size); Buffer : constant Util.Streams.Buffered.Buffer_Access := Stream.Get_Buffer; begin return Create_Blob (Data => Buffer (Buffer'First .. Buffer'First + Size - 1)); end Get_Blob; end ADO.Utils.Streams;
Update Read procedure to use the Implicit_Dereference support in Util.Refs
Update Read procedure to use the Implicit_Dereference support in Util.Refs
Ada
apache-2.0
stcarrez/ada-ado
d5f2f40935db95b1de1126f9ad502e5129e9f588
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 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.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Declare the Set_Type procedure on the column definition
Declare the Set_Type procedure on the column definition
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
51a72122d094bec6e5775d3b47fe7ef9640b1fad
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for 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 Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (User.Get_Id); Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for 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 Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
83220549b9501258798f384eed64066e35b5657d
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Fix memory leak in unit test
Fix memory leak in unit test
Ada
apache-2.0
Letractively/ada-security
1bf4bb1b3dc07ebdb64785552c1ba84424e02826
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Strings; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Nodes.Dump; procedure Render is use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Count : Natural := 0; Html_Mode : Boolean := True; Html_Toc : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; Indent : Natural := 3; Dump_Tree : Boolean := False; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Output.Set_Indent_Level (Indent); if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (Html_Toc); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; procedure Dump (Doc : in Wiki.Documents.Document) is procedure Write (Indent : in Positive; Line : in Wiki.Strings.WString) is S : constant String := Wiki.Strings.To_String (Line); begin Ada.Text_IO.Set_Col (Ada.Text_Io.Count (Indent)); Ada.Text_IO.Put_Line (S); end Write; procedure Dump is new Wiki.Nodes.Dump (Write); begin Doc.Iterate (Dump'Access); end Dump; procedure Render_File (Name : in String) is Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). if Name /= "--" then Input.Open (Name, "WCEM=8"); end if; Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Dump_Tree then Dump (Doc); elsif Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Render_File; begin for I in 1 .. Arg_Count loop declare Param : constant String := Ada.Command_Line.Argument (I); begin if Param = "-m" then Syntax := Wiki.SYNTAX_MARKDOWN; elsif Param = "-M" then Syntax := Wiki.SYNTAX_MEDIA_WIKI; elsif Param = "-c" then Syntax := Wiki.SYNTAX_CREOLE; elsif Param = "-d" then Syntax := Wiki.SYNTAX_DOTCLEAR; elsif Param = "-H" then Syntax := Wiki.SYNTAX_HTML; elsif Param = "-T" then Syntax := Wiki.SYNTAX_TEXTILE; elsif Param = "-g" then Syntax := Wiki.SYNTAX_GOOGLE; elsif Param = "-t" then Html_Mode := False; elsif Param = "-z" then Html_Toc := True; elsif Param = "-s" then Style := To_Unbounded_String (Param); elsif Param = "--" then Render_File (Param); elsif Param = "-0" then Indent := 0; elsif Param = "-1" then Indent := 1; elsif Param = "-2" then Indent := 2; elsif Param = "-dump" then Dump_Tree := True; elsif Param (Param'First) = '-' then Usage; return; else Render_File (Param); end if; end; end loop; if Count = 0 then Usage; end if; end Render;
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Strings; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Nodes.Dump; procedure Render is use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); procedure Dump (Doc : in Wiki.Documents.Document); procedure Render_File (Name : in String); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Count : Natural := 0; Html_Mode : Boolean := True; Html_Toc : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; Indent : Natural := 3; Dump_Tree : Boolean := False; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [options] {wiki-file}"); Ada.Text_IO.Put_Line (" -0, -1, -2 Controls the indentation level"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); Ada.Text_IO.Put_Line (" -dump Dump the document tree"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Output.Set_Indent_Level (Indent); if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (Html_Toc); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; procedure Dump (Doc : in Wiki.Documents.Document) is procedure Write (Indent : in Positive; Line : in Wiki.Strings.WString); procedure Write (Indent : in Positive; Line : in Wiki.Strings.WString) is S : constant String := Wiki.Strings.To_String (Line); begin Ada.Text_IO.Set_Col (Ada.Text_IO.Count (Indent)); Ada.Text_IO.Put_Line (S); end Write; procedure Dump is new Wiki.Nodes.Dump (Write); begin Doc.Iterate (Dump'Access); end Dump; procedure Render_File (Name : in String) is Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). if Name /= "--" then Input.Open (Name, "WCEM=8"); end if; Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Dump_Tree then Dump (Doc); elsif Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Render_File; begin for I in 1 .. Arg_Count loop declare Param : constant String := Ada.Command_Line.Argument (I); begin if Param = "-m" then Syntax := Wiki.SYNTAX_MARKDOWN; elsif Param = "-M" then Syntax := Wiki.SYNTAX_MEDIA_WIKI; elsif Param = "-c" then Syntax := Wiki.SYNTAX_CREOLE; elsif Param = "-d" then Syntax := Wiki.SYNTAX_DOTCLEAR; elsif Param = "-H" then Syntax := Wiki.SYNTAX_HTML; elsif Param = "-T" then Syntax := Wiki.SYNTAX_TEXTILE; elsif Param = "-g" then Syntax := Wiki.SYNTAX_GOOGLE; elsif Param = "-t" then Html_Mode := False; elsif Param = "-z" then Html_Toc := True; elsif Param = "-s" then Style := To_Unbounded_String (Param); elsif Param = "--" then Render_File (Param); elsif Param = "-0" then Indent := 0; elsif Param = "-1" then Indent := 1; elsif Param = "-2" then Indent := 2; elsif Param = "-dump" then Dump_Tree := True; elsif Param (Param'First) = '-' then Usage; return; else Render_File (Param); end if; end; end loop; if Count = 0 then Usage; end if; end Render;
Update the program usage
Update the program usage
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f35b10d241d02877998122959b889a6fed1aab21
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Questions.Services.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Questions.Services.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 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.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Update the testsuite
Update the testsuite
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
b44440928ce3e0ae3b0c4bfff3e056181a228ddf
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Writer (Document : in out Html_Renderer; Writer : in Wiki.Writers.Html_Writer_Type_Access) is begin Document.Writer := Writer; end Set_Writer; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); case Level is when 1 => Document.Writer.Write_Wide_Element ("h1", Header); when 2 => Document.Writer.Write_Wide_Element ("h2", Header); when 3 => Document.Writer.Write_Wide_Element ("h3", Header); when 4 => Document.Writer.Write_Wide_Element ("h4", Header); when 5 => Document.Writer.Write_Wide_Element ("h5", Header); when 6 => Document.Writer.Write_Wide_Element ("h6", Header); when others => Document.Writer.Write_Wide_Element ("h3", Header); end case; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Html_Renderer) is begin Document.Writer.Write ("<br />"); end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Writer.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Writer.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Writer.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Writer.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Writer.Start_Element ("ol"); else Document.Writer.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Writer.End_Element ("p"); end if; if Document.Has_Item then Document.Writer.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Writer.End_Element ("ol"); else Document.Writer.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Writer.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Writer.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); Document.Writer.Start_Element ("hr"); Document.Writer.End_Element ("hr"); end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is Exists : Boolean; URI : Unbounded_Wide_Wide_String; begin Document.Open_Paragraph; Document.Writer.Start_Element ("a"); if Length (Title) > 0 then Document.Writer.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; Document.Links.Make_Page_Link (Link, URI, Exists); Document.Writer.Write_Wide_Attribute ("href", URI); Document.Writer.Write_Wide_Text (Name); Document.Writer.End_Element ("a"); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Html_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) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Writer.Start_Element ("img"); if Length (Alt) > 0 then Document.Writer.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Writer.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Writer.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Writer.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Writer.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Writer.End_Element ("img"); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Writer.Start_Element ("q"); if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Writer.Write_Wide_Attribute ("cite", Link); end if; Document.Writer.Write_Wide_Text (Quote); Document.Writer.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Open_Paragraph; for I in Format'Range loop if Format (I) then Document.Writer.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Document.Writer.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Document.Writer.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Writer.Write (Text); else Document.Writer.Start_Element ("pre"); Document.Writer.Write_Wide_Text (Text); Document.Writer.End_Element ("pre"); end if; end Add_Preformatted; overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes); begin Document.Html_Level := Document.Html_Level + 1; if Name = "p" then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name))); while Wiki.Attributes.Has_Element (Iter) loop Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; end Start_Element; overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String) is begin Document.Html_Level := Document.Html_Level - 1; if Name = "p" then Document.Has_Paragraph := False; Document.Need_Paragraph := True; end if; Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name))); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); case Level is when 1 => Document.Writer.Write_Wide_Element ("h1", Header); when 2 => Document.Writer.Write_Wide_Element ("h2", Header); when 3 => Document.Writer.Write_Wide_Element ("h3", Header); when 4 => Document.Writer.Write_Wide_Element ("h4", Header); when 5 => Document.Writer.Write_Wide_Element ("h5", Header); when 6 => Document.Writer.Write_Wide_Element ("h6", Header); when others => Document.Writer.Write_Wide_Element ("h3", Header); end case; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Html_Renderer) is begin Document.Writer.Write ("<br />"); end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Writer.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Writer.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Writer.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Writer.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Writer.Start_Element ("ol"); else Document.Writer.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Writer.End_Element ("p"); end if; if Document.Has_Item then Document.Writer.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Writer.End_Element ("ol"); else Document.Writer.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Writer.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Writer.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); Document.Writer.Start_Element ("hr"); Document.Writer.End_Element ("hr"); end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is Exists : Boolean; URI : Unbounded_Wide_Wide_String; begin Document.Open_Paragraph; Document.Writer.Start_Element ("a"); if Length (Title) > 0 then Document.Writer.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; Document.Links.Make_Page_Link (Link, URI, Exists); Document.Writer.Write_Wide_Attribute ("href", URI); Document.Writer.Write_Wide_Text (Name); Document.Writer.End_Element ("a"); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Html_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) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Writer.Start_Element ("img"); if Length (Alt) > 0 then Document.Writer.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Writer.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Writer.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Writer.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Writer.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Writer.End_Element ("img"); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Writer.Start_Element ("q"); if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Writer.Write_Wide_Attribute ("cite", Link); end if; Document.Writer.Write_Wide_Text (Quote); Document.Writer.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Open_Paragraph; for I in Format'Range loop if Format (I) then Document.Writer.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Document.Writer.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Document.Writer.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Writer.Write (Text); else Document.Writer.Start_Element ("pre"); Document.Writer.Write_Wide_Text (Text); Document.Writer.End_Element ("pre"); end if; end Add_Preformatted; overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes); begin Document.Html_Level := Document.Html_Level + 1; if Name = "p" then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name))); while Wiki.Attributes.Has_Element (Iter) loop Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; end Start_Element; overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String) is begin Document.Html_Level := Document.Html_Level - 1; if Name = "p" then Document.Has_Paragraph := False; Document.Need_Paragraph := True; end if; Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name))); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Rename Set_Writer into Set_Output_Stream
Rename Set_Writer into Set_Output_Stream
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f7087c46f62e602db9f5d16864e1519861e71f38
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.Directories; use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, ";", Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String) return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Unbounded_String; -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; use Ada.Strings.Fixed; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Length (Result) > 0 then Append (Result, ';'); end if; Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return To_String (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or Directory = "./" then if Name (Name'First) /= '/' then return Name; else return Compose (Directory, Name (Name'First + 1 .. Name'Last)); end if; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2015, 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 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 Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
Update the header and invert some if condition as per AdaControl recommendation
Update the header and invert some if condition as per AdaControl recommendation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d7d763d622cae600195b1cadf1da04e97fa4b3ef
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Properties; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Druss.Commands.Status.Wan_Status'Access); end Initialize; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Druss.Commands.Status.Wan_Status'Access); end Initialize; end Druss.Commands;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/bbox-ada-api
8355d75b2b0c7cc7f8d7efcde536304768e71646
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Add F_RANGE_ADDR and F_MODE
Add F_RANGE_ADDR and F_MODE
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2f9522f06fb51d90bd015ee70026b760191aae2b
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Declare and implement Initialize_Logs to configure the log manager and setup some default behavior for logs
Declare and implement Initialize_Logs to configure the log manager and setup some default behavior for logs
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat