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
|
---|---|---|---|---|---|---|---|---|---|
04b43a6f3e32e179645fb08231c04e45ad89befd
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
end Wiki.Render.Html;
|
Use the Wiki.Render.Links package
|
Use the Wiki.Render.Links package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
807aae4483153b349b291087dc205171d344fc1c
|
matp/src/events/mat-events-probes.adb
|
matp/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- 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 Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := new MAT.Frames.Targets.Target_Frames;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
-- ------------------------------
-- Get the target frames.
-- ------------------------------
function Get_Target_Frames (Client : in Probe_Manager_Type)
return MAT.Frames.Targets.Target_Frames_Access is
begin
return Client.Frames;
end Get_Target_Frames;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Prev_Id := 0;
Client.Event.Old_Size := 0;
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
Client.Frames.Insert (Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
-- Look at the probe definition to gather the target address size.
Client.Addr_Size := MAT.Events.T_UINT32;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then
Client.Addr_Size := Def.Kind;
exit;
end if;
end;
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Get the size of a target address (4 or 8 bytes).
-- ------------------------------
function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is
begin
return Client.Addr_Size;
end Get_Address_Size;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014, 2015, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := new MAT.Frames.Targets.Target_Frames;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
-- ------------------------------
-- Get the target frames.
-- ------------------------------
function Get_Target_Frames (Client : in Probe_Manager_Type)
return MAT.Frames.Targets.Target_Frames_Access is
begin
return Client.Frames;
end Get_Target_Frames;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Prev_Id := 0;
Client.Event.Old_Size := 0;
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
Client.Frames.Insert (Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
-- Look at the probe definition to gather the target address size.
Client.Addr_Size := MAT.Events.T_UINT32;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then
Client.Addr_Size := Def.Kind;
exit;
end if;
end;
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Get the size of a target address (4 or 8 bytes).
-- ------------------------------
function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is
begin
return Client.Addr_Size;
end Get_Address_Size;
end MAT.Events.Probes;
|
Fix compilation warning with GNAT 2018
|
Fix compilation warning with GNAT 2018
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ee8e3abbf1ef05a1eaaa6630e44d9566449b1239
|
samples/bean.adb
|
samples/bean.adb
|
-----------------------------------------------------------------------
-- bean - A simple bean example
-- 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 body Bean is
use EL.Objects;
FIRST_NAME : constant String := "firstName";
LAST_NAME : constant String := "lastName";
AGE : constant String := "age";
Null_Object : Object;
function Create_Person (First_Name, Last_Name : String;
Age : Natural) return Person_Access is
begin
return new Person '(First_Name => To_Unbounded_String (First_Name),
Last_Name => To_Unbounded_String (Last_Name),
Age => Age);
end Create_Person;
-- Get the value identified by the name.
function Get_Value (From : Person; Name : String) return EL.Objects.Object is
begin
if Name = FIRST_NAME then
return To_Object (From.First_Name);
elsif Name = LAST_NAME then
return To_Object (From.Last_Name);
elsif Name = AGE then
return To_Object (From.Age);
else
return Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
procedure Set_Value (From : in out Person;
Name : in String;
Value : in EL.Objects.Object) is
begin
if Name = FIRST_NAME then
From.First_Name := To_Unbounded_String (Value);
elsif Name = LAST_NAME then
From.Last_Name := To_Unbounded_String (Value);
elsif Name = AGE then
From.Age := Natural (To_Integer (Value));
end if;
end Set_Value;
-- Function to format a string
function Format (Arg : EL.Objects.Object) return EL.Objects.Object is
S : constant String := To_String (Arg);
begin
return To_Object ("[" & S & "]");
end Format;
end Bean;
|
-----------------------------------------------------------------------
-- bean - A simple bean example
-- 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 body Bean is
use EL.Objects;
FIRST_NAME : constant String := "firstName";
LAST_NAME : constant String := "lastName";
AGE : constant String := "age";
Null_Object : Object;
function Create_Person (First_Name, Last_Name : String;
Age : Natural) return Person_Access is
begin
return new Person '(First_Name => To_Unbounded_String (First_Name),
Last_Name => To_Unbounded_String (Last_Name),
Age => Age);
end Create_Person;
-- Get the value identified by the name.
function Get_Value (From : Person; Name : String) return EL.Objects.Object is
begin
if Name = FIRST_NAME then
return To_Object (From.First_Name);
elsif Name = LAST_NAME then
return To_Object (From.Last_Name);
elsif Name = AGE then
return To_Object (From.Age);
else
return Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
procedure Set_Value (From : in out Person;
Name : in String;
Value : in EL.Objects.Object) is
begin
if Name = FIRST_NAME then
From.First_Name := To_Unbounded_String (Value);
elsif Name = LAST_NAME then
From.Last_Name := To_Unbounded_String (Value);
elsif Name = AGE then
From.Age := Natural (To_Integer (Value));
end if;
end Set_Value;
-- Function to format a string
function Format (Arg : EL.Objects.Object) return EL.Objects.Object is
S : constant String := To_String (Arg);
begin
return To_Object ("[" & S & "]");
end Format;
end Bean;
|
Fix indentation
|
Fix indentation
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
539935c5593fee29d162d3eef3a403e7f172ffc4
|
src/orka/implementation/orka-jobs-executors.adb
|
src/orka/implementation/orka-jobs-executors.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Tags;
-- with Ada.Text_IO;
with Orka.Containers.Bounded_Vectors;
with Orka.Futures;
with Orka.Logging;
package body Orka.Jobs.Executors is
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Executor);
function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is
Result : Job_Ptr := Element;
begin
while Result.Dependent /= Null_Job loop
Result := Result.Dependent;
end loop;
return Result;
end Get_Root_Dependent;
procedure Execute_Jobs
(Name : String;
Kind : Queues.Executor_Kind;
Queue : Queues.Queue_Ptr)
is
use type Ada.Real_Time.Time;
use type Futures.Status;
use Ada.Exceptions;
Pair : Queues.Pair;
Stop : Boolean := False;
Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair;
package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job);
-- T0, T1, T2 : Ada.Real_Time.Time;
begin
loop
-- T0 := Ada.Real_Time.Clock;
Queue.Dequeue (Kind) (Pair, Stop);
exit when Stop;
declare
Job : Job_Ptr renames Pair.Job;
Future : Futures.Pointers.Reference renames Pair.Future.Get;
Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all);
Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job);
procedure Enqueue (Element : Job_Ptr) is
begin
Jobs.Append (Element);
end Enqueue;
procedure Set_Root_Dependent (Last_Job : Job_Ptr) is
Root_Dependents : Vectors.Vector (Capacity => Jobs.Length);
procedure Set_Dependencies (Elements : Vectors.Element_Array) is
begin
Last_Job.Set_Dependencies (Dependency_Array (Elements));
end Set_Dependencies;
begin
for Job of Jobs loop
declare
Root : constant Job_Ptr := Get_Root_Dependent (Job);
begin
if not (for some Dependent of Root_Dependents => Root = Dependent) then
Root_Dependents.Append (Root);
end if;
end;
end loop;
Root_Dependents.Query (Set_Dependencies'Access);
end Set_Root_Dependent;
Tag : String renames Ada.Tags.Expanded_Name (Job'Tag);
begin
-- T1 := Ada.Real_Time.Clock;
-- Ada.Text_IO.Put_Line (Name & " executing job " & Tag);
if Future.Current_Status = Futures.Waiting then
Promise.Set_Status (Futures.Running);
end if;
if Future.Current_Status = Futures.Running then
begin
Job.Execute (Enqueue'Access);
exception
when Error : others =>
Promise.Set_Failed (Error);
Messages.Insert (Logging.Error,
Kind'Image & " job " & Tag & " " & Exception_Information (Error));
end;
else
Messages.Insert (Warning,
Kind'Image & " job " & Tag & " already " & Future.Current_Status'Image);
end if;
-- T2 := Ada.Real_Time.Clock;
-- declare
-- Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0);
-- Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1);
-- begin
-- Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms");
-- end;
if Job.Dependent /= Null_Job then
-- Make the root dependents of the jobs in Jobs
-- dependencies of Job.Dependent
if not Jobs.Empty then
Set_Root_Dependent (Job.Dependent);
end if;
-- If another job depends on this job, decrement its dependencies counter
-- and if it has reached zero then it can be scheduled
if Job.Dependent.Decrement_Dependencies then
pragma Assert (Jobs.Empty);
Queue.Enqueue (Job.Dependent, Pair.Future);
end if;
elsif Jobs.Empty then
Promise.Set_Status (Futures.Done);
-- Ada.Text_IO.Put_Line (Name & " completed graph with job " & Tag);
else
-- If the job has enqueued new jobs, we need to create an
-- empty job which has the root dependents of these new jobs
-- as dependencies. This is so that the empty job will be the
-- last job that is given Pair.Future
Set_Root_Dependent (Create_Empty_Job);
end if;
if not Jobs.Empty then
for Job of Jobs loop
Queue.Enqueue (Job, Pair.Future);
end loop;
end if;
Free (Job);
end;
-- Finalize the smart pointer (Pair.Future) to reduce the number
-- of references to the Future object
Pair := Null_Pair;
end loop;
exception
when Error : others =>
Messages.Insert (Logging.Error, Exception_Information (Error));
end Execute_Jobs;
end Orka.Jobs.Executors;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Tags;
-- with Ada.Text_IO;
with Orka.Containers.Bounded_Vectors;
with Orka.Futures;
with Orka.Logging;
package body Orka.Jobs.Executors is
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Executor);
function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is
Result : Job_Ptr := Element;
begin
while Result.Dependent /= Null_Job loop
Result := Result.Dependent;
end loop;
return Result;
end Get_Root_Dependent;
procedure Execute_Jobs
(Name : String;
Kind : Queues.Executor_Kind;
Queue : Queues.Queue_Ptr)
is
use type Ada.Real_Time.Time;
use type Futures.Status;
use Ada.Exceptions;
Pair : Queues.Pair;
Stop : Boolean := False;
Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair;
package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job);
-- T0, T1, T2 : Ada.Real_Time.Time;
begin
loop
-- T0 := Ada.Real_Time.Clock;
Queue.Dequeue (Kind) (Pair, Stop);
exit when Stop;
declare
Job : Job_Ptr renames Pair.Job;
Future : Futures.Pointers.Reference renames Pair.Future.Get;
Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all);
Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job);
procedure Enqueue (Element : Job_Ptr) is
begin
Jobs.Append (Element);
end Enqueue;
procedure Set_Root_Dependent (Last_Job : Job_Ptr) is
Root_Dependents : Vectors.Vector (Capacity => Jobs.Length);
procedure Set_Dependencies (Elements : Vectors.Element_Array) is
begin
Last_Job.Set_Dependencies (Dependency_Array (Elements));
end Set_Dependencies;
begin
for Job of Jobs loop
declare
Root : constant Job_Ptr := Get_Root_Dependent (Job);
begin
if not (for some Dependent of Root_Dependents => Root = Dependent) then
Root_Dependents.Append (Root);
end if;
end;
end loop;
Root_Dependents.Query (Set_Dependencies'Access);
end Set_Root_Dependent;
Tag : String renames Ada.Tags.Expanded_Name (Job'Tag);
begin
-- T1 := Ada.Real_Time.Clock;
-- Ada.Text_IO.Put_Line (Name & " executing job " & Tag);
if Future.Current_Status = Futures.Waiting then
Promise.Set_Status (Futures.Running);
end if;
if Future.Current_Status = Futures.Running then
begin
Job.Execute (Enqueue'Access);
exception
when Error : others =>
Promise.Set_Failed (Error);
Messages.Insert (Logging.Error,
Kind'Image & " job " & Tag & " " & Exception_Information (Error));
end;
else
Messages.Insert (Warning,
Kind'Image & " job " & Tag & " already " & Future.Current_Status'Image);
end if;
-- T2 := Ada.Real_Time.Clock;
-- declare
-- Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0);
-- Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1);
-- begin
-- Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms");
-- end;
if Job.Dependent /= Null_Job then
-- Make the root dependents of the jobs in Jobs
-- dependencies of Job.Dependent
if not Jobs.Empty then
Set_Root_Dependent (Job.Dependent);
end if;
-- If another job depends on this job, decrement its dependencies counter
-- and if it has reached zero then it can be scheduled
if Job.Dependent.Decrement_Dependencies then
pragma Assert (Jobs.Empty);
-- Ada.Text_IO.Put_Line (Name & " job " & Tag & " enqueuing dependent " &
-- Ada.Tags.Expanded_Name (Job.Dependent'Tag));
Queue.Enqueue (Job.Dependent, Pair.Future);
end if;
elsif Jobs.Empty then
Promise.Set_Status (Futures.Done);
-- Ada.Text_IO.Put_Line (Name & " completed graph with job " & Tag);
else
-- If the job has enqueued new jobs, we need to create an
-- empty job which has the root dependents of these new jobs
-- as dependencies. This is so that the empty job will be the
-- last job that is given Pair.Future
Set_Root_Dependent (Create_Empty_Job);
end if;
if not Jobs.Empty then
for Job of Jobs loop
-- Ada.Text_IO.Put_Line (Name & " job " & Tag & " enqueuing job " &
-- Ada.Tags.Expanded_Name (Job'Tag));
Queue.Enqueue (Job, Pair.Future);
end loop;
end if;
Free (Job);
end;
-- Finalize the smart pointer (Pair.Future) to reduce the number
-- of references to the Future object
Pair := Null_Pair;
end loop;
exception
when Error : others =>
Messages.Insert (Logging.Error, Exception_Information (Error));
end Execute_Jobs;
end Orka.Jobs.Executors;
|
Add some commented debugging prints in package Orka.Jobs.Executors
|
orka: Add some commented debugging prints in package Orka.Jobs.Executors
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
d83c538a130283d4ddf10b2cb093e5ddedd23b3c
|
src/gen-model-list.adb
|
src/gen-model-list.adb
|
-----------------------------------------------------------------------
-- gen-model-list -- List bean interface for model objects
-- 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.
-----------------------------------------------------------------------
package body Gen.Model.List is
-- ------------------------------
-- Compare the two definitions.
-- ------------------------------
function "<" (Left, Right : in T_Access) return Boolean is
Left_Name : constant String := Left.Get_Name;
Right_Name : constant String := Right.Get_Name;
begin
return Left_Name < Right_Name;
end "<";
-- ------------------------------
-- Get the first item of the list
-- ------------------------------
function First (Def : List_Definition) return Cursor is
begin
return Def.Nodes.First;
end First;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : List_Definition) return Natural is
Count : constant Natural := Natural (From.Nodes.Length);
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out List_Definition;
Index : in Natural) is
begin
From.Row := Index;
if Index > 0 then
declare
Current : constant T_Access := From.Nodes.Element (Index - 1);
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Current.all'Access;
begin
Current.Row_Index := Index;
From.Value_Bean := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
else
From.Value_Bean := Util.Beans.Objects.Null_Object;
end if;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : List_Definition) return Util.Beans.Objects.Object is
begin
return From.Value_Bean;
end Get_Row;
-- ------------------------------
-- 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 : List_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "size" then
return Util.Beans.Objects.To_Object (From.Get_Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append the item in the list
-- ------------------------------
procedure Append (Def : in out List_Definition;
Item : in T_Access) is
begin
Def.Nodes.Append (Item);
end Append;
-- ------------------------------
-- Sort the list of items on their names.
-- ------------------------------
procedure Sort (List : in out List_Definition) is
begin
Sorting.Sort (List.Nodes);
end Sort;
procedure Sort_On (List : in out List_Definition) is
package Sorting is new Vectors.Generic_Sorting;
begin
Sorting.Sort (List.Nodes);
end Sort_On;
-- ------------------------------
-- Find a definition given the name.
-- Returns the definition object or null.
-- ------------------------------
function Find (Def : in List_Definition;
Name : in String) return T_Access is
Iter : Vectors.Cursor := Def.Nodes.First;
begin
while Vectors.Has_Element (Iter) loop
if Vectors.Element (Iter).Get_Name = Name then
return Vectors.Element (Iter);
end if;
Vectors.Next (Iter);
end loop;
return null;
end Find;
-- ------------------------------
-- Iterate over the elements of the list executing the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (Def : in List_Definition;
Process : not null access procedure (Item : in T_Access)) is
Iter : Vectors.Cursor := Def.Nodes.First;
begin
while Vectors.Has_Element (Iter) loop
Process (Vectors.Element (Iter));
Vectors.Next (Iter);
end loop;
end Iterate;
end Gen.Model.List;
|
-----------------------------------------------------------------------
-- gen-model-list -- List bean interface for model objects
-- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Model.List is
-- ------------------------------
-- Make an iterator for the list.
-- ------------------------------
function Iterate (Container : in List_Definition)
return List_Iterator.Forward_Iterator'Class is
begin
return Result : constant Iterator := (List => Container.Self);
end Iterate;
-- ------------------------------
-- Make an iterator for the list.
-- ------------------------------
function Element_Value (Container : in List_Definition;
Pos : in Cursor)
return T_Access is
pragma Unreferenced (Container);
begin
return Element (Pos);
end Element_Value;
overriding
function First (Object : in Iterator) return Cursor is
begin
return Object.List.First;
end First;
overriding
function Next (Object : in Iterator;
Pos : in Cursor) return Cursor is
pragma Unreferenced (Object);
C : Cursor := Pos;
begin
Next (C);
return C;
end Next;
-- ------------------------------
-- Compare the two definitions.
-- ------------------------------
function "<" (Left, Right : in T_Access) return Boolean is
Left_Name : constant String := Left.Get_Name;
Right_Name : constant String := Right.Get_Name;
begin
return Left_Name < Right_Name;
end "<";
-- ------------------------------
-- Get the first item of the list
-- ------------------------------
function First (Def : List_Definition) return Cursor is
begin
return Def.Nodes.First;
end First;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : List_Definition) return Natural is
Count : constant Natural := Natural (From.Nodes.Length);
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out List_Definition;
Index : in Natural) is
begin
From.Row := Index;
if Index > 0 then
declare
Current : constant T_Access := From.Nodes.Element (Index - 1);
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Current.all'Access;
begin
Current.Row_Index := Index;
From.Value_Bean := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
else
From.Value_Bean := Util.Beans.Objects.Null_Object;
end if;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : List_Definition) return Util.Beans.Objects.Object is
begin
return From.Value_Bean;
end Get_Row;
-- ------------------------------
-- 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 : List_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "size" then
return Util.Beans.Objects.To_Object (From.Get_Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append the item in the list
-- ------------------------------
procedure Append (Def : in out List_Definition;
Item : in T_Access) is
begin
Def.Nodes.Append (Item);
end Append;
-- ------------------------------
-- Sort the list of items on their names.
-- ------------------------------
procedure Sort (List : in out List_Definition) is
begin
Sorting.Sort (List.Nodes);
end Sort;
procedure Sort_On (List : in out List_Definition) is
package Sorting is new Vectors.Generic_Sorting;
begin
Sorting.Sort (List.Nodes);
end Sort_On;
-- ------------------------------
-- Find a definition given the name.
-- Returns the definition object or null.
-- ------------------------------
function Find (Def : in List_Definition;
Name : in String) return T_Access is
Iter : Vectors.Cursor := Def.Nodes.First;
begin
while Vectors.Has_Element (Iter) loop
if Vectors.Element (Iter).Get_Name = Name then
return Vectors.Element (Iter);
end if;
Vectors.Next (Iter);
end loop;
return null;
end Find;
-- ------------------------------
-- Iterate over the elements of the list executing the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (Def : in List_Definition;
Process : not null access procedure (Item : in T_Access)) is
Iter : Vectors.Cursor := Def.Nodes.First;
begin
while Vectors.Has_Element (Iter) loop
Process (Vectors.Element (Iter));
Vectors.Next (Iter);
end loop;
end Iterate;
end Gen.Model.List;
|
Implement the Iterate, Element_Value, First and Next operation for Ada 2012 iterators
|
Implement the Iterate, Element_Value, First and Next operation for Ada 2012 iterators
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
8f4e9f307d00a2c1614a72c0db3ccae2d69517ee
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Declare the Hide_TOC procedure
|
Declare the Hide_TOC procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
977f0cffcd97c45e09ddda91dc5913fbd0ba0e9a
|
src/gen-utils-gnat.adb
|
src/gen-utils-gnat.adb
|
-----------------------------------------------------------------------
-- gen-utils-gnat -- GNAT utilities
-- Copyright (C) 2011, 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Gen.Configs;
with Csets;
with Snames;
with Namet;
with Prj.Pars;
with Prj.Tree;
with Prj.Env;
with Prj.Util;
with Makeutl;
with Output;
package body Gen.Utils.GNAT is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT");
Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref;
Main_Project : Prj.Project_Id;
-- ------------------------------
-- Initialize the GNAT project runtime for reading the GNAT project tree.
-- Configure it according to the dynamo configuration properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS,
DEFAULT_GNAT_PROJECT_DIR);
begin
Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs);
Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data;
Prj.Tree.Initialize (Project_Node_Tree);
Output.Set_Standard_Error;
Csets.Initialize;
Snames.Initialize;
Prj.Initialize (Makeutl.Project_Tree);
Prj.Env.Add_Directories (Project_Node_Tree.Project_Path, Project_Dirs);
end Initialize;
-- ------------------------------
-- Read the GNAT project file identified by <b>Project_File_Name</b> and get
-- in <b>Project_List</b> an ordered list of absolute project paths used by
-- the root project.
-- ------------------------------
procedure Read_GNAT_Project_List (Project_File_Name : in String;
Project_List : out Project_Info_Vectors.Vector) is
procedure Recursive_Add (Proj : in Prj.Project_Id;
Dummy : in out Boolean);
function Get_Variable_Value (Proj : in Prj.Project_Id;
Name : in String) return String;
function Get_Project_Name (Proj : in Prj.Project_Id) return String;
-- Get the variable value represented by the name <b>Name</b>.
-- ??? There are probably other efficient ways to get this but I couldn't find them.
function Get_Variable_Value (Proj : in Prj.Project_Id;
Name : in String) return String is
use type Prj.Variable_Id;
Current : Prj.Variable_Id;
The_Variable : Prj.Variable;
In_Tree : constant Prj.Project_Tree_Ref := Makeutl.Project_Tree;
begin
Current := Proj.Decl.Variables;
while Current /= Prj.No_Variable loop
The_Variable := In_Tree.Variable_Elements.Table (Current);
if Namet.Get_Name_String (The_Variable.Name) = Name then
return Prj.Util.Value_Of (The_Variable.Value, "");
end if;
Current := The_Variable.Next;
end loop;
return "";
end Get_Variable_Value;
-- ------------------------------
-- Get the project name from the GNAT project name or from the "name" project variable.
-- ------------------------------
function Get_Project_Name (Proj : in Prj.Project_Id) return String is
Name : constant String := Get_Variable_Value (Proj, "name");
begin
if Name'Length > 0 then
return Name;
else
return Namet.Get_Name_String (Proj.Name);
end if;
end Get_Project_Name;
-- ------------------------------
-- Add the full path of the GNAT project in the project list.
-- ------------------------------
procedure Recursive_Add (Proj : in Prj.Project_Id;
Dummy : in out Boolean) is
pragma Unreferenced (Dummy);
Path : constant String := Namet.Get_Name_String (Proj.Path.Name);
Name : constant String := Get_Project_Name (Proj);
Project : Project_Info;
begin
Log.Info ("Using GNAT project: {0} - {1}", Path, Name);
Project.Path := To_Unbounded_String (Path);
Project.Name := To_Unbounded_String (Name);
Project_List.Append (Project);
end Recursive_Add;
procedure For_All_Projects is
new Prj.For_Every_Project_Imported (Boolean, Recursive_Add);
use type Prj.Project_Id;
Flags : Prj.Processing_Flags;
begin
Log.Info ("Reading GNAT project {0}", Project_File_Name);
Flags := Prj.Create_Flags (Report_Error => null,
When_No_Sources => Prj.Error,
Require_Obj_Dirs => Prj.Silent,
Allow_Invalid_External => Prj.Silent,
Missing_Source_Files => Prj.Silent);
-- Parse the GNAT project files and build the tree.
Prj.Pars.Parse (Project => Main_Project,
In_Tree => Makeutl.Project_Tree,
Project_File_Name => Project_File_Name,
Flags => Flags,
In_Node_Tree => Project_Node_Tree);
if Main_Project /= Prj.No_Project then
declare
Dummy : Boolean := False;
begin
-- Scan the tree to get the list of projects (in dependency order).
For_All_Projects (Main_Project, Dummy, Imported_First => True);
end;
end if;
end Read_GNAT_Project_List;
end Gen.Utils.GNAT;
|
-----------------------------------------------------------------------
-- gen-utils-gnat -- GNAT utilities
-- Copyright (C) 2011, 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Gen.Configs;
with Csets;
with Snames;
with Namet;
with Prj.Pars;
with Prj.Tree;
with Prj.Env;
with Prj.Util;
with Makeutl;
with Output;
with GNAT.OS_Lib; use GNAT.OS_Lib;
package body Gen.Utils.GNAT is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT");
Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref;
Main_Project : Prj.Project_Id;
Project_Tree : constant Prj.Project_Tree_Ref :=
new Prj.Project_Tree_Data (Is_Root_Tree => True);
-- The project tree
-- ------------------------------
-- Initialize the GNAT project runtime for reading the GNAT project tree.
-- Configure it according to the dynamo configuration properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS,
DEFAULT_GNAT_PROJECT_DIR);
begin
Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs);
Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data;
Prj.Tree.Initialize (Project_Node_Tree);
Output.Set_Standard_Error;
Csets.Initialize;
Snames.Initialize;
Prj.Initialize (Project_Tree);
Prj.Env.Add_Directories (Makeutl.Root_Environment.Project_Path, Project_Dirs);
end Initialize;
-- ------------------------------
-- Read the GNAT project file identified by <b>Project_File_Name</b> and get
-- in <b>Project_List</b> an ordered list of absolute project paths used by
-- the root project.
-- ------------------------------
procedure Read_GNAT_Project_List (Project_File_Name : in String;
Project_List : out Project_Info_Vectors.Vector) is
procedure Recursive_Add (Proj : in Prj.Project_Id;
Tree : in Prj.Project_Tree_Ref;
Dummy : in out Boolean);
function Get_Variable_Value (Proj : in Prj.Project_Id;
Name : in String) return String;
function Get_Project_Name (Proj : in Prj.Project_Id) return String;
-- Get the variable value represented by the name <b>Name</b>.
-- ??? There are probably other efficient ways to get this but I couldn't find them.
function Get_Variable_Value (Proj : in Prj.Project_Id;
Name : in String) return String is
use type Prj.Variable_Id;
Current : Prj.Variable_Id;
The_Variable : Prj.Variable;
begin
Current := Proj.Decl.Variables;
while Current /= Prj.No_Variable loop
The_Variable := Project_Tree.Shared.Variable_Elements.Table (Current);
if Namet.Get_Name_String (The_Variable.Name) = Name then
return Prj.Util.Value_Of (The_Variable.Value, "");
end if;
Current := The_Variable.Next;
end loop;
return "";
end Get_Variable_Value;
-- ------------------------------
-- Get the project name from the GNAT project name or from the "name" project variable.
-- ------------------------------
function Get_Project_Name (Proj : in Prj.Project_Id) return String is
Name : constant String := Get_Variable_Value (Proj, "name");
begin
if Name'Length > 0 then
return Name;
else
return Namet.Get_Name_String (Proj.Name);
end if;
end Get_Project_Name;
-- ------------------------------
-- Add the full path of the GNAT project in the project list.
-- ------------------------------
procedure Recursive_Add (Proj : in Prj.Project_Id;
Tree : in Prj.Project_Tree_Ref;
Dummy : in out Boolean) is
pragma Unreferenced (Tree, Dummy);
Path : constant String := Namet.Get_Name_String (Proj.Path.Name);
Name : constant String := Get_Project_Name (Proj);
Project : Project_Info;
begin
Log.Info ("Using GNAT project: {0} - {1}", Path, Name);
Project.Path := To_Unbounded_String (Path);
Project.Name := To_Unbounded_String (Name);
Project_List.Append (Project);
end Recursive_Add;
procedure For_All_Projects is
new Prj.For_Every_Project_Imported (Boolean, Recursive_Add);
use type Prj.Project_Id;
begin
Log.Info ("Reading GNAT project {0}", Project_File_Name);
-- Parse the GNAT project files and build the tree.
Prj.Pars.Parse (Project => Main_Project,
In_Tree => Project_Tree,
Project_File_Name => Project_File_Name,
Packages_To_Check => null,
Env => Makeutl.Root_Environment,
In_Node_Tree => Project_Node_Tree);
if Main_Project /= Prj.No_Project then
declare
Dummy : Boolean := False;
begin
-- Scan the tree to get the list of projects (in dependency order).
For_All_Projects (Main_Project, Project_Tree,
Imported_First => True, With_State => Dummy);
end;
end if;
end Read_GNAT_Project_List;
end Gen.Utils.GNAT;
|
Update to use the gcc 5.2.0 GNAT project support
|
Update to use the gcc 5.2.0 GNAT project support
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
c35f97f2284d8a66245ecf8556db6ae85a2cab6a
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
with AWA.Tags.Beans;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
-- List of answers associated with the question.
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
-- The question.
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
Add the list of tags associated with the question
|
Add the list of tags associated with the question
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
1f5a22681dcf509117697616115523eafc4feb92
|
src/aws/asf-requests-web.adb
|
src/aws/asf-requests-web.adb
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWS.Attachments.Extend;
with AWS.Containers.Tables;
with AWS.Parameters;
with Util.Strings;
with ASF.Parts.Web;
package body ASF.Requests.Web is
function Get_Parameter (R : Request; Name : String) return String is
begin
return AWS.Status.Parameter (R.Data.all, Name);
end Get_Parameter;
-- ------------------------------
-- Iterate over the request parameters and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Parameters (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
procedure Process_Wrapper (Name, Value : in String);
procedure Process_Wrapper (Name, Value : in String) is
Last : Natural := Value'First;
Pos : Natural;
begin
while Last <= Value'Last loop
Pos := Util.Strings.Index (Value, ASCII.NUL, Last);
if Pos > 0 then
Process (Name, Value (Last .. Pos - 1));
Last := Pos + 1;
else
Process (Name, Value (Last .. Value'Last));
return;
end if;
end loop;
end Process_Wrapper;
P : constant AWS.Parameters.List := AWS.Status.Parameters (Req.Data.all);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (P),
"" & ASCII.NUL, Process_Wrapper'Access);
end Iterate_Parameters;
-- ------------------------------
-- Set the AWS data received to initialize the request object.
-- ------------------------------
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data) is
begin
Req.Data := Data;
Req.Headers := AWS.Status.Header (Data.all);
end Set_Request;
-- ------------------------------
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
-- ------------------------------
function Get_Method (Req : in Request) return String is
begin
return AWS.Status.Method (Req.Data.all);
end Get_Method;
-- ------------------------------
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
-- ------------------------------
function Get_Protocol (Req : in Request) return String is
begin
return AWS.Status.HTTP_Version (Req.Data.all);
end Get_Protocol;
-- ------------------------------
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
-- ------------------------------
function Get_Request_URI (Req : in Request) return String is
begin
return AWS.Status.URI (Req.Data.all);
end Get_Request_URI;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Header (Req : in Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name);
begin
if Values'Length > 0 then
return To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Req.Headers.Iterate_Names (", ",
Process => Process);
end Iterate_Headers;
-- ------------------------------
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Headers (Req : in Request;
Name : in String) return String is
begin
return AWS.Headers.Get_Values (Req.Headers, Name);
end Get_Headers;
-- ------------------------------
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
-- ------------------------------
function Get_Remote_Addr (Req : in Request) return String is
begin
return AWS.Status.Peername (Req.Data.all);
end Get_Remote_Addr;
-- ------------------------------
-- Get the number of parts included in the request.
-- ------------------------------
function Get_Part_Count (Req : in Request) return Natural is
begin
return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all));
end Get_Part_Count;
-- ------------------------------
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process);
end Process_Part;
-- ------------------------------
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
procedure Process_Part (E : in AWS.Attachments.Element);
procedure Process_Part (E : in AWS.Attachments.Element) is
Name : constant String := AWS.Attachments.Extend.Get_Name (E);
begin
if Id = Name then
ASF.Parts.Web.Process_Part (E, Process);
end if;
end Process_Part;
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
AWS.Attachments.Iterate (Attachs, Process_Part'Access);
-- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process);
end Process_Part;
-- ------------------------------
-- 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 Request;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
AWS.Status.Read_Body (D => Stream.Data.all,
Buffer => Into,
Last => Last);
end Read;
overriding
function Create_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access is
Result : constant ASF.Streams.Input_Stream_Access := new ASF.Streams.Input_Stream;
begin
Result.Initialize (Output => null,
Input => Req'Unrestricted_Access,
Size => 8192);
return Result;
end Create_Input_Stream;
end ASF.Requests.Web;
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWS.Attachments.Extend;
with AWS.Containers.Tables;
with AWS.Parameters;
with Util.Strings;
with ASF.Parts.Web;
package body ASF.Requests.Web is
function Get_Parameter (R : Request; Name : String) return String is
begin
return AWS.Status.Parameter (R.Data.all, Name);
end Get_Parameter;
-- ------------------------------
-- Iterate over the request parameters and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Parameters (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
procedure Process_Wrapper (Name, Value : in String);
procedure Process_Wrapper (Name, Value : in String) is
Last : Natural := Value'First;
Pos : Natural;
begin
while Last <= Value'Last loop
Pos := Util.Strings.Index (Value, ASCII.NUL, Last);
if Pos > 0 then
Process (Name, Value (Last .. Pos - 1));
Last := Pos + 1;
else
Process (Name, Value (Last .. Value'Last));
return;
end if;
end loop;
end Process_Wrapper;
P : constant AWS.Parameters.List := AWS.Status.Parameters (Req.Data.all);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (P),
"" & ASCII.NUL, Process_Wrapper'Access);
end Iterate_Parameters;
-- ------------------------------
-- Set the AWS data received to initialize the request object.
-- ------------------------------
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data) is
begin
Req.Data := Data;
Req.Headers := AWS.Status.Header (Data.all);
end Set_Request;
-- ------------------------------
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
-- ------------------------------
function Get_Method (Req : in Request) return String is
begin
return AWS.Status.Method (Req.Data.all);
end Get_Method;
-- ------------------------------
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
-- ------------------------------
function Get_Protocol (Req : in Request) return String is
begin
return AWS.Status.HTTP_Version (Req.Data.all);
end Get_Protocol;
-- ------------------------------
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
-- ------------------------------
function Get_Request_URI (Req : in Request) return String is
begin
return AWS.Status.URI (Req.Data.all);
end Get_Request_URI;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Header (Req : in Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name);
begin
if Values'Length > 0 then
return To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Req.Headers.Iterate_Names (", ",
Process => Process);
end Iterate_Headers;
-- ------------------------------
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Headers (Req : in Request;
Name : in String) return String is
begin
return AWS.Headers.Get_Values (Req.Headers, Name);
end Get_Headers;
-- ------------------------------
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
-- ------------------------------
function Get_Remote_Addr (Req : in Request) return String is
begin
return AWS.Status.Peername (Req.Data.all);
end Get_Remote_Addr;
-- ------------------------------
-- Get the number of parts included in the request.
-- ------------------------------
function Get_Part_Count (Req : in Request) return Natural is
begin
return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all));
end Get_Part_Count;
-- ------------------------------
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process);
end Process_Part;
-- ------------------------------
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
procedure Process_Part (E : in AWS.Attachments.Element);
procedure Process_Part (E : in AWS.Attachments.Element) is
Name : constant String := AWS.Attachments.Extend.Get_Name (E);
begin
if Id = Name then
ASF.Parts.Web.Process_Part (E, Process);
end if;
end Process_Part;
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
AWS.Attachments.Iterate (Attachs, Process_Part'Access);
-- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process);
end Process_Part;
-- ------------------------------
-- 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 Request;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
AWS.Status.Read_Body (D => Stream.Data.all,
Buffer => Into,
Last => Last);
end Read;
overriding
function Create_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access is
Result : constant ASF.Streams.Input_Stream_Access := new ASF.Streams.Input_Stream;
begin
Result.Initialize (Input => Req'Unrestricted_Access,
Size => 8192);
return Result;
end Create_Input_Stream;
end ASF.Requests.Web;
|
Update initialization of the input stream
|
Update initialization of the input stream
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
448ec9799f1b972f681c7bb9ab9ef6c328cf5d0b
|
src/ado-queries-loaders.ads
|
src/ado-queries-loaders.ads
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Drivers.Connections;
package ADO.Queries.Loaders is
generic
Path : String;
Sha1 : String;
package File is
Name : aliased constant String := Path;
Hash : aliased constant String := Sha1;
File : aliased Query_File;
end File;
generic
Name : String;
File : Query_File_Access;
package Query is
Query_Name : aliased constant String := Name;
Query : aliased Query_Definition;
end Query;
-- Read the query definition.
procedure Read_Query (Manager : in out Query_Manager;
Into : in Query_Definition_Access);
-- 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);
-- 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 (Manager : in out Query_Manager_Access;
Config : in ADO.Drivers.Connections.Configuration'Class);
-- Find the query identified by the given name.
function Find_Query (Name : in String) return Query_Definition_Access;
private
-- Returns True if the XML query file must be reloaded.
function Is_Modified (File : in out Query_File_Info) return Boolean;
-- Read the query file and all the associated definitions.
procedure Read_Query (Manager : in out Query_Manager;
File : in out Query_File_Info);
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Drivers.Connections;
package ADO.Queries.Loaders is
generic
Path : String;
Sha1 : String;
package File is
Name : aliased constant String := Path;
Hash : aliased constant String := Sha1;
File : aliased Query_File;
end File;
generic
Name : String;
File : Query_File_Access;
package Query is
Query_Name : aliased constant String := Name;
Query : aliased Query_Definition;
end Query;
-- Read the query definition.
procedure Read_Query (Manager : in Query_Manager;
Into : in Query_Definition_Access);
-- 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);
-- 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 (Manager : in out Query_Manager;
Config : in ADO.Drivers.Connections.Configuration'Class);
-- Find the query identified by the given name.
function Find_Query (Name : in String) return Query_Definition_Access;
private
-- Returns True if the XML query file must be reloaded.
function Is_Modified (File : in out Query_File_Info) return Boolean;
-- Read the query file and all the associated definitions.
procedure Read_Query (Manager : in Query_Manager;
File : in out Query_File_Info);
end ADO.Queries.Loaders;
|
Update to use the Query_Manager instead of Query_Manager_Access
|
Update to use the Query_Manager instead of Query_Manager_Access
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
9db9afe64e636e384b545a2446cf832d54e32aa0
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- 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 ADO.Sessions;
with AWA.Storages.Models;
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- 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 ADO.Sessions;
with AWA.Storages.Models;
-- == Store Service ==
-- The `AWA.Storages.Stores` package defines the interface that a store must implement to
-- be able to save and retrieve a data content.
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
6e82754842bbf3216f7a3c6f7223108c3647e280
|
tools/timekey.adb
|
tools/timekey.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Calendar;
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Time_IO.RFC_3339;
with Natools.Time_Keys;
procedure Timekey is
procedure Process (Line : in String);
-- Guess the type of Line and convert it to or from type.
procedure Process_Input;
-- Read lines from current input and process them.
Input_Processed : Boolean := False;
Empty : Boolean := True;
Verbose : Boolean := False;
procedure Process (Line : in String) is
begin
if Verbose then
Ada.Text_IO.Put (Line);
end if;
if Natools.Time_Keys.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_IO.RFC_3339.Image
(Natools.Time_Keys.To_Time (Line), Duration'Aft, False));
elsif Natools.Time_IO.RFC_3339.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_Keys.To_Key (Natools.Time_IO.RFC_3339.Value (Line)));
end if;
end Process;
procedure Process_Input is
begin
if Input_Processed then
return;
else
Input_Processed := True;
end if;
begin
loop
Process (Ada.Text_IO.Get_Line);
end loop;
exception
when Ada.Text_IO.End_Error => null;
end;
end Process_Input;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
Arg : constant String := Ada.Command_Line.Argument (I);
begin
if Arg = "-" then
Empty := False;
Process_Input;
elsif Arg = "-v" then
Verbose := True;
else
Empty := False;
Process (Arg);
end if;
end;
end loop;
if Empty then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Verbose then
Ada.Text_IO.Put
(Natools.Time_IO.RFC_3339.Image (Now, Duration'Aft, False)
& " => ");
end if;
Ada.Text_IO.Put_Line (Natools.Time_Keys.To_Key (Now));
end;
end if;
end Timekey;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Calendar;
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Time_IO.RFC_3339;
with Natools.Time_Keys;
procedure Timekey is
procedure Process (Line : in String);
-- Guess the type of Line and convert it to or from type.
procedure Process_Input;
-- Read lines from current input and process them.
Input_Processed : Boolean := False;
Empty : Boolean := True;
Verbose : Boolean := False;
Subsecond_Digits : Natural := Duration'Aft;
procedure Process (Line : in String) is
begin
if Verbose then
Ada.Text_IO.Put (Line);
end if;
if Natools.Time_Keys.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_IO.RFC_3339.Image
(Natools.Time_Keys.To_Time (Line), Subsecond_Digits, False));
elsif Natools.Time_IO.RFC_3339.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_Keys.To_Key (Natools.Time_IO.RFC_3339.Value (Line)));
end if;
end Process;
procedure Process_Input is
begin
if Input_Processed then
return;
else
Input_Processed := True;
end if;
begin
loop
Process (Ada.Text_IO.Get_Line);
end loop;
exception
when Ada.Text_IO.End_Error => null;
end;
end Process_Input;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
Arg : constant String := Ada.Command_Line.Argument (I);
begin
if Arg = "-" then
Empty := False;
Process_Input;
elsif Arg = "-v" then
Verbose := True;
else
Empty := False;
Process (Arg);
end if;
end;
end loop;
if Empty then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Verbose then
Ada.Text_IO.Put
(Natools.Time_IO.RFC_3339.Image (Now, Subsecond_Digits, False)
& " => ");
end if;
Ada.Text_IO.Put_Line (Natools.Time_Keys.To_Key (Now));
end;
end if;
end Timekey;
|
refactor the number of displayed subsecond digits
|
tools/timekey: refactor the number of displayed subsecond digits
|
Ada
|
isc
|
faelys/natools
|
ac14ad190b6c380f10182c9a3d997ce166609ba0
|
src/asf-converters-dates.adb
|
src/asf-converters-dates.adb
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Exceptions;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with Util.Dates.Formats;
with Util.Log.Loggers;
with ASF.Applications.Main;
package body ASF.Converters.Dates is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Converters.Dates");
function Get_Date_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String;
function Get_Time_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String;
-- ------------------------------
-- Get the format to print the date.
-- ------------------------------
function Get_Date_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String is
begin
case Mode is
when DEFAULT =>
return Bundle.Get ("faces.dates.default_date_format", "%x");
when SHORT =>
return Bundle.Get ("faces.dates.short_date_format", "%d/%m/%Y");
when MEDIUM =>
return Bundle.Get ("faces.dates.medium_date_format", "%b %d, %Y");
when LONG =>
return Bundle.Get ("faces.dates.long_date_format", "%B %d, %Y");
when FULL =>
return Bundle.Get ("faces.dates.full_date_format", "%A, %B %d, %Y");
end case;
end Get_Date_Format;
-- ------------------------------
-- Get the format to print the time.
-- ------------------------------
function Get_Time_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String is
begin
case Mode is
when DEFAULT =>
return Bundle.Get ("faces.dates.default_time_format", "%X");
when SHORT =>
return Bundle.Get ("faces.dates.short_time_format", "%H:%M");
when MEDIUM =>
return Bundle.Get ("faces.dates.medium_time_format", "%H:%M");
when LONG =>
return Bundle.Get ("faces.dates.long_time_format", "%H:%M:%S");
when FULL =>
return Bundle.Get ("faces.dates.full_time_format", "%H:%M:%S %Z");
end case;
end Get_Time_Format;
-- ------------------------------
-- Get the date format pattern that must be used for formatting a date on the given component.
-- ------------------------------
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Bundle : in ASF.Locales.Bundle;
Component : in ASF.Components.Base.UIComponent'Class) return String is
begin
case Convert.Format is
when BOTH =>
return Get_Date_Format (Convert.Time_Style, Bundle);
when TIME =>
return Get_Time_Format (Convert.Time_Style, Bundle);
when DATE =>
return Get_Date_Format (Convert.Date_Style, Bundle);
when CONVERTER_PATTERN =>
return Ada.Strings.Unbounded.To_String (Convert.Pattern);
when COMPONENT_FORMAT =>
return Component.Get_Attribute (Context => Context,
Name => "format",
Default => "%x");
end case;
end Get_Pattern;
-- ------------------------------
-- Get the locale that must be used to format the date.
-- ------------------------------
function Get_Locale (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Locales.Locale is
use type Util.Locales.Locale;
begin
if Convert.Locale /= Util.Locales.NULL_LOCALE then
return Convert.Locale;
else
return Context.Get_Locale;
end if;
end Get_Locale;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Locale : constant Util.Locales.Locale
:= Date_Converter'Class (Convert).Get_Locale (Context);
Bundle : ASF.Locales.Bundle;
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "asf",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
Pattern : constant String
:= Date_Converter'Class (Convert).Get_Pattern (Context, Bundle, Component);
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Result : constant String := Util.Dates.Formats.Format (Pattern, Date, Bundle);
begin
return Result;
end;
exception
when E : others =>
raise Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
-- ------------------------------
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Convert, Context, Component, Value);
begin
Log.Error ("String to date conversion is not yet implemented");
return Util.Beans.Objects.Null_Object;
end To_Object;
-- ------------------------------
-- Create a date converter.
-- ------------------------------
function Create_Date_Converter (Date : in Style_Type;
Time : in Style_Type;
Format : in Format_Type;
Locale : in String;
Pattern : in String) return Date_Converter_Access is
use Ada.Strings.Unbounded;
L : constant Util.Locales.Locale := Util.Locales.Get_Locale (Locale);
begin
if Pattern'Length > 0 then
return new Date_Converter '(Date_Style => Date,
Time_Style => Time,
Locale => L,
Format => CONVERTER_PATTERN,
Pattern => To_Unbounded_String (Pattern));
else
return new Date_Converter '(Date_Style => Date,
Time_Style => Time,
Format => Format,
Locale => L,
Pattern => Null_Unbounded_String);
end if;
end Create_Date_Converter;
end ASF.Converters.Dates;
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- Copyright (C) 2011, 2012, 2013, 2014, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Exceptions;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with Util.Dates.Formats;
with Util.Log.Loggers;
with ASF.Applications.Main;
package body ASF.Converters.Dates is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Converters.Dates");
function Get_Date_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String;
function Get_Time_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String;
-- ------------------------------
-- Get the format to print the date.
-- ------------------------------
function Get_Date_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String is
begin
case Mode is
when DEFAULT =>
return Bundle.Get ("faces.dates.default_date_format", "%x");
when SHORT =>
return Bundle.Get ("faces.dates.short_date_format", "%d/%m/%Y");
when MEDIUM =>
return Bundle.Get ("faces.dates.medium_date_format", "%b %d, %Y");
when LONG =>
return Bundle.Get ("faces.dates.long_date_format", "%B %d, %Y");
when FULL =>
return Bundle.Get ("faces.dates.full_date_format", "%A, %B %d, %Y");
end case;
end Get_Date_Format;
-- ------------------------------
-- Get the format to print the time.
-- ------------------------------
function Get_Time_Format (Mode : in Style_Type;
Bundle : in ASF.Locales.Bundle) return String is
begin
case Mode is
when DEFAULT =>
return Bundle.Get ("faces.dates.default_time_format", "%X");
when SHORT =>
return Bundle.Get ("faces.dates.short_time_format", "%H:%M");
when MEDIUM =>
return Bundle.Get ("faces.dates.medium_time_format", "%H:%M");
when LONG =>
return Bundle.Get ("faces.dates.long_time_format", "%H:%M:%S");
when FULL =>
return Bundle.Get ("faces.dates.full_time_format", "%H:%M:%S %Z");
end case;
end Get_Time_Format;
-- ------------------------------
-- Get the date format pattern that must be used for formatting a date on the given component.
-- ------------------------------
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Bundle : in ASF.Locales.Bundle;
Component : in ASF.Components.Base.UIComponent'Class) return String is
begin
case Convert.Format is
when BOTH =>
return Get_Date_Format (Convert.Time_Style, Bundle);
when TIME =>
return Get_Time_Format (Convert.Time_Style, Bundle);
when DATE =>
return Get_Date_Format (Convert.Date_Style, Bundle);
when CONVERTER_PATTERN =>
return Ada.Strings.Unbounded.To_String (Convert.Pattern);
when COMPONENT_FORMAT =>
return Component.Get_Attribute (Context => Context,
Name => "format",
Default => "%x");
end case;
end Get_Pattern;
-- ------------------------------
-- Get the locale that must be used to format the date.
-- ------------------------------
function Get_Locale (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Locales.Locale is
use type Util.Locales.Locale;
begin
if Convert.Locale /= Util.Locales.NULL_LOCALE then
return Convert.Locale;
else
return Context.Get_Locale;
end if;
end Get_Locale;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Locale : constant Util.Locales.Locale
:= Date_Converter'Class (Convert).Get_Locale (Context);
Bundle : ASF.Locales.Bundle;
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "asf",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
Pattern : constant String
:= Date_Converter'Class (Convert).Get_Pattern (Context, Bundle, Component);
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Result : constant String := Util.Dates.Formats.Format (Pattern, Date, Bundle);
begin
return Result;
end;
exception
when E : others =>
raise Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
-- ------------------------------
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object is
Locale : constant Util.Locales.Locale
:= Date_Converter'Class (Convert).Get_Locale (Context);
Bundle : ASF.Locales.Bundle;
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "asf",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E));
end;
-- Convert the string to a date here so that we can raise an Invalid_Conversion exception.
declare
Pattern : constant String
:= Date_Converter'Class (Convert).Get_Pattern (Context, Bundle, Component);
Date : Util.Dates.Date_Record;
begin
Log.Debug ("Date conversion '{0}' with pattern '{1}'", Value, Pattern);
Date := Util.Dates.Formats.Parse (Pattern => Pattern, Date => Value, Bundle => Bundle);
return Util.Beans.Objects.Time.To_Object (Date.Date);
exception
when E : others =>
Log.Error ("Date '{0}' does not match pattern '{1}'", Value, Pattern);
raise Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end;
end To_Object;
-- ------------------------------
-- Create a date converter.
-- ------------------------------
function Create_Date_Converter (Date : in Style_Type;
Time : in Style_Type;
Format : in Format_Type;
Locale : in String;
Pattern : in String) return Date_Converter_Access is
use Ada.Strings.Unbounded;
L : constant Util.Locales.Locale := Util.Locales.Get_Locale (Locale);
begin
if Pattern'Length > 0 then
return new Date_Converter '(Date_Style => Date,
Time_Style => Time,
Locale => L,
Format => CONVERTER_PATTERN,
Pattern => To_Unbounded_String (Pattern));
else
return new Date_Converter '(Date_Style => Date,
Time_Style => Time,
Format => Format,
Locale => L,
Pattern => Null_Unbounded_String);
end if;
end Create_Date_Converter;
end ASF.Converters.Dates;
|
Fix the To_Object function to implement the conversion and parsing of a string into a date
|
Fix the To_Object function to implement the conversion and parsing of a string into a date
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4b077c934b324e83abe65877885a35bbfb3575e9
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null and then Length (AID) > 0 then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
if Auth = null then
Context.Set_Context (F.Manager, null);
else
Context.Set_Context (F.Manager, Auth.all'Access);
end if;
declare
URL : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URL_Permission (URL'Length)
:= URL_Permission '(Len => URL'Length, URL => URL);
begin
if not F.Manager.Has_Permission (Context, Perm) then
if Auth = null then
-- No permission and no principal, redirect to the login page.
Log.Info ("Page need authentication on {0}", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
else
Log.Info ("Deny access on {0}", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
end if;
return;
end if;
Log.Debug ("Access granted on {0}", URL);
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null and then Length (AID) > 0 then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
if Auth = null then
Context.Set_Context (F.Manager, null);
else
Context.Set_Context (F.Manager, Auth.all'Access);
end if;
declare
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
Perm : constant Policies.URLs.URL_Permission (URL'Length)
:= URL_Permission '(Len => URL'Length, URL => URL);
begin
if not F.Manager.Has_Permission (Context, Perm) then
if Auth = null then
-- No permission and no principal, redirect to the login page.
Log.Info ("Page need authentication on {0}", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
else
Log.Info ("Deny access on {0}", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
end if;
return;
end if;
Log.Debug ("Access granted on {0}", URL);
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Add the servlet path in the URL to check the permission
|
Add the servlet path in the URL to check the permission
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
ea6d298c9864e8ff9107064a937423f74e5c96d4
|
src/util-streams-sockets.ads
|
src/util-streams-sockets.ads
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- 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.Finalization;
with GNAT.Sockets;
-- The <b>Util.Streams.Sockets</b> package defines a socket stream.
package Util.Streams.Sockets is
-- -----------------------
-- Socket stream
-- -----------------------
-- The <b>Socket_Stream</b> is an output/input stream that reads or writes
-- to or from a socket.
type Socket_Stream is limited new Output_Stream and Input_Stream with private;
-- Initialize the socket stream.
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type);
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type);
-- Close the socket stream.
overriding
procedure Close (Stream : in out Socket_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Socket_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Sock : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Socket_Stream);
end Util.Streams.Sockets;
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with GNAT.Sockets;
-- The <b>Util.Streams.Sockets</b> package defines a socket stream.
package Util.Streams.Sockets is
-- -----------------------
-- Socket stream
-- -----------------------
-- The <b>Socket_Stream</b> is an output/input stream that reads or writes
-- to or from a socket.
type Socket_Stream is limited new Output_Stream and Input_Stream with private;
-- Initialize the socket stream.
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type);
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type);
-- Close the socket stream.
overriding
procedure Close (Stream : in out Socket_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Socket_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Sock : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Socket_Stream);
end Util.Streams.Sockets;
|
Fix compilation error with GNAT 2015
|
Fix compilation error with GNAT 2015
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9b36069259317a04e97ec8cafd3ee45531eabf95
|
src/el-variables-default.adb
|
src/el-variables-default.adb
|
-----------------------------------------------------------------------
-- EL.Variables -- Default Variable Mapper
-- 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 EL.Expressions;
package body EL.Variables.Default is
overriding
procedure Bind (Mapper : in out Default_Variable_Mapper;
Name : in String;
Value : in EL.Objects.Object) is
Expr : constant EL.Expressions.Value_Expression
:= EL.Expressions.Create_ValueExpression (Value);
begin
Mapper.Map.Include (Key => To_Unbounded_String (Name),
New_Item => EL.Expressions.Expression (Expr));
end Bind;
overriding
function Get_Variable (Mapper : Default_Variable_Mapper;
Name : Unbounded_String)
return EL.Expressions.Expression is
C : constant Variable_Maps.Cursor := Mapper.Map.Find (Name);
begin
if not Variable_Maps.Has_Element (C) then
if Mapper.Next_Mapper /= null then
return Mapper.Next_Mapper.Get_Variable (Name);
end if;
-- Avoid raising an exception if we can't resolve a variable.
-- Instead, return a null expression. This speeds up the resolution and
-- creation of Ada bean in ASF framework (cost of exception is high compared to this).
return E : EL.Expressions.Expression;
end if;
return Variable_Maps.Element (C);
end Get_Variable;
overriding
procedure Set_Variable (Mapper : in out Default_Variable_Mapper;
Name : in Unbounded_String;
Value : in EL.Expressions.Expression) is
begin
Mapper.Map.Include (Key => Name,
New_Item => Value);
end Set_Variable;
-- ------------------------------
-- Set the next variable mapper that will be used to resolve a variable if
-- the current variable mapper does not find a variable.
-- ------------------------------
procedure Set_Next_Variable_Mapper (Mapper : in out Default_Variable_Mapper;
Next_Mapper : in Variable_Mapper_Access) is
begin
Mapper.Next_Mapper := Next_Mapper;
end Set_Next_Variable_Mapper;
end EL.Variables.Default;
|
-----------------------------------------------------------------------
-- EL.Variables -- Default Variable Mapper
-- 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 EL.Expressions;
package body EL.Variables.Default is
overriding
procedure Bind (Mapper : in out Default_Variable_Mapper;
Name : in String;
Value : in EL.Objects.Object) is
Expr : constant EL.Expressions.Value_Expression
:= EL.Expressions.Create_ValueExpression (Value);
begin
Mapper.Map.Include (Key => To_Unbounded_String (Name),
New_Item => EL.Expressions.Expression (Expr));
end Bind;
overriding
function Get_Variable (Mapper : Default_Variable_Mapper;
Name : Unbounded_String)
return EL.Expressions.Expression is
C : constant Variable_Maps.Cursor := Mapper.Map.Find (Name);
begin
if not Variable_Maps.Has_Element (C) then
if Mapper.Next_Mapper /= null then
return Mapper.Next_Mapper.all.Get_Variable (Name);
end if;
-- Avoid raising an exception if we can't resolve a variable.
-- Instead, return a null expression. This speeds up the resolution and
-- creation of Ada bean in ASF framework (cost of exception is high compared to this).
return E : EL.Expressions.Expression;
end if;
return Variable_Maps.Element (C);
end Get_Variable;
overriding
procedure Set_Variable (Mapper : in out Default_Variable_Mapper;
Name : in Unbounded_String;
Value : in EL.Expressions.Expression) is
begin
Mapper.Map.Include (Key => Name,
New_Item => Value);
end Set_Variable;
-- ------------------------------
-- Set the next variable mapper that will be used to resolve a variable if
-- the current variable mapper does not find a variable.
-- ------------------------------
procedure Set_Next_Variable_Mapper (Mapper : in out Default_Variable_Mapper;
Next_Mapper : in Variable_Mapper_Access) is
begin
Mapper.Next_Mapper := Next_Mapper;
end Set_Next_Variable_Mapper;
end EL.Variables.Default;
|
Fix Issue 1:build failed with gcc 4.7
|
Fix Issue 1:build failed with gcc 4.7
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
9484a0809bb3adb6a3ef9a784cd34040fc36989a
|
regtests/util_harness.adb
|
regtests/util_harness.adb
|
-----------------------------------------------------------------------
-- Util -- Utilities
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with AUnit.Reporter.Text;
with AUnit.Run;
with Util.Testsuite;
with Util.Measures;
procedure Util_Harness is
procedure Runner is new AUnit.Run.Test_Runner (Util.Testsuite.Suite);
Reporter : AUnit.Reporter.Text.Text_Reporter;
Perf : aliased Util.Measures.Measure_Set;
begin
Util.Measures.Set_Current (Perf'Unchecked_Access);
Runner (Reporter);
Util.Measures.Write (Perf, "Util measures", Ada.Text_IO.Standard_Output);
end Util_Harness;
|
-----------------------------------------------------------------------
-- Util -- Utilities
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Text_IO;
with AUnit;
with AUnit.Reporter.Text;
with AUnit.Run;
with Util.Testsuite;
with Util.Measures;
procedure Util_Harness is
use type AUnit.Status;
function Runner is new AUnit.Run.Test_Runner_With_Status (Util.Testsuite.Suite);
Reporter : AUnit.Reporter.Text.Text_Reporter;
Perf : aliased Util.Measures.Measure_Set;
Result : AUnit.Status;
begin
Util.Measures.Set_Current (Perf'Unchecked_Access);
Result := Runner (Reporter, True);
Util.Measures.Write (Perf, "Util measures", Ada.Text_IO.Standard_Output);
-- Program exit status reflects the testsuite result
if Result /= AUnit.Success then
Ada.Command_Line.Set_Exit_Status (1);
else
Ada.Command_Line.Set_Exit_Status (0);
end if;
end Util_Harness;
|
Fix exit status of unit test tool
|
Fix exit status of unit test tool
|
Ada
|
apache-2.0
|
Letractively/ada-util,stcarrez/ada-util,Letractively/ada-util,flottokarotto/ada-util,stcarrez/ada-util,flottokarotto/ada-util
|
6962934873a5dfe9bc7031e7386dc6d2f1f82c20
|
src/natools-smaz_implementations-base_64.adb
|
src/natools-smaz_implementations-base_64.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2016-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Implementations.Base_64 is
package Tools renames Natools.Smaz_Implementations.Base_64_Tools;
use type Ada.Streams.Stream_Element_Offset;
use type Tools.Base_64_Digit;
----------------------
-- Public Interface --
----------------------
procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Verbatim_Length : out Natural;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Ignored : String (1 .. 2);
Offset_Backup : Ada.Streams.Stream_Element_Offset;
Finished : Boolean;
begin
Tools.Next_Digit_Or_End (Input, Offset, Code, Finished);
if Finished then
Code := Base_64_Tools.Base_64_Digit'Last;
Verbatim_Length := 0;
return;
end if;
if Code <= Last_Code then
Verbatim_Length := 0;
elsif Variable_Length_Verbatim then
if Code < 63 then
Verbatim_Length := 63 - Natural (Code);
else
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) + 63 - Natural (Last_Code);
end if;
Code := 0;
elsif Code = 63 then
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) * 3 + 3;
Code := 0;
elsif Code = 62 then
Offset_Backup := Offset;
Tools.Decode_Single (Input, Offset, Ignored (1), Code);
Verbatim_Length := Natural (Code) * 3 + 1;
Offset := Offset_Backup;
Code := 0;
else
Offset_Backup := Offset;
Verbatim_Length := (61 - Natural (Code)) * 4;
Tools.Decode_Double (Input, Offset, Ignored, Code);
Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2;
Offset := Offset_Backup;
Code := 0;
end if;
end Read_Code;
procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String)
is
Ignored : Tools.Base_64_Digit;
Output_Index : Natural := Output'First - 1;
begin
if Output'Length mod 3 = 1 then
Tools.Decode_Single
(Input, Offset, Output (Output_Index + 1), Ignored);
Output_Index := Output_Index + 1;
elsif Output'Length mod 3 = 2 then
Tools.Decode_Double
(Input, Offset,
Output (Output_Index + 1 .. Output_Index + 2), Ignored);
Output_Index := Output_Index + 2;
end if;
if Output_Index < Output'Last then
Tools.Decode
(Input, Offset, Output (Output_Index + 1 .. Output'Last));
end if;
end Read_Verbatim;
procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive)
is
Code : Tools.Base_64_Digit;
begin
for I in 1 .. Tools.Image_Length (Verbatim_Length) loop
Tools.Next_Digit (Input, Offset, Code);
end loop;
end Skip_Verbatim;
function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count is
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Run_Count : constant Natural
:= (Input_Length + Largest_Run - 1) / Largest_Run;
Last_Run_Size : constant Positive
:= Input_Length - (Run_Count - 1) * Largest_Run;
Last_Run_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Last_Run_Size > Largest_Single then 2 else 1);
begin
return Ada.Streams.Stream_Element_Count (Run_Count)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Last_Run_Size) + Last_Run_Header_Size;
end;
else
declare
Largest_Prefix : constant Natural
:= (case Input_Length mod 3 is
when 1 => 15 * 3 + 1,
when 2 => ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2,
when others => 0);
Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Largest_Prefix > 0 then 1 else 0);
Largest_Run : constant Positive := 64 * 3;
Prefix_Size : constant Natural
:= Natural'Min (Largest_Prefix, Input_Length);
Run_Count : constant Natural
:= (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run;
begin
if Run_Count > 0 then
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size)
+ Ada.Streams.Stream_Element_Count (Run_Count - 1)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Input_Length - Prefix_Size
- (Run_Count - 1) * Largest_Run)
+ 2;
else
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size);
end if;
end;
end if;
end Verbatim_Size;
procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is
begin
Output (Offset) := Tools.Image (Code);
Offset := Offset + 1;
end Write_Code;
procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Index : Positive := Input'First;
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Length, Last : Natural;
begin
while Index in Input'Range loop
Length := Positive'Min (Largest_Run, Input'Last + 1 - Index);
if Length > Largest_Single then
Write_Code (Output, Offset, 63);
Write_Code
(Output, Offset,
Tools.Base_64_Digit (Length - Largest_Single - 1));
else
Write_Code
(Output, Offset,
Tools.Base_64_Digit (63 - Length));
end if;
if Length mod 3 = 1 then
Tools.Encode_Single (Input (Index), 0, Output, Offset);
Index := Index + 1;
Length := Length - 1;
elsif Length mod 3 = 2 then
Tools.Encode_Double
(Input (Index .. Index + 1), 0, Output, Offset);
Index := Index + 2;
Length := Length - 2;
end if;
if Length > 0 then
Last := Index + Length - 1;
Tools.Encode (Input (Index .. Last), Output, Offset);
Index := Last + 1;
end if;
end loop;
end;
else
if Input'Length mod 3 = 1 then
declare
Extra_Blocks : constant Natural
:= Natural'Min (15, Input'Length / 3);
begin
Output (Offset) := Tools.Image (62);
Offset := Offset + 1;
Tools.Encode_Single
(Input (Index), Tools.Single_Byte_Padding (Extra_Blocks),
Output, Offset);
Index := Index + 1;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
elsif Input'Length mod 3 = 2 then
declare
Extra_Blocks : constant Natural := Natural'Min
(Input'Length / 3,
(62 - Natural (Last_Code)) * 4 - 1);
begin
Output (Offset)
:= Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4));
Offset := Offset + 1;
Tools.Encode_Double
(Input (Index .. Index + 1),
Tools.Double_Byte_Padding (Extra_Blocks mod 4),
Output, Offset);
Index := Index + 2;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
end if;
pragma Assert ((Input'Last + 1 - Index) mod 3 = 0);
while Index <= Input'Last loop
declare
Block_Count : constant Natural
:= Natural'Min (64, (Input'Last + 1 - Index) / 3);
begin
Output (Offset) := Tools.Image (63);
Output (Offset + 1)
:= Tools.Image (Tools.Base_64_Digit (Block_Count - 1));
Offset := Offset + 2;
Tools.Encode
(Input (Index .. Index + Block_Count * 3 - 1),
Output, Offset);
Index := Index + Block_Count * 3;
end;
end loop;
end if;
end Write_Verbatim;
end Natools.Smaz_Implementations.Base_64;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Implementations.Base_64 is
package Tools renames Natools.Smaz_Implementations.Base_64_Tools;
use type Ada.Streams.Stream_Element_Offset;
use type Tools.Base_64_Digit;
----------------------
-- Public Interface --
----------------------
procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Verbatim_Length : out Natural;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Ignored : String (1 .. 2);
Offset_Backup : Ada.Streams.Stream_Element_Offset;
Finished : Boolean;
begin
Tools.Next_Digit_Or_End (Input, Offset, Code, Finished);
if Finished then
Code := Base_64_Tools.Base_64_Digit'Last;
Verbatim_Length := 0;
return;
end if;
if Code <= Last_Code then
Verbatim_Length := 0;
elsif Variable_Length_Verbatim then
if Code < 63 then
Verbatim_Length := 63 - Natural (Code);
else
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) + 63 - Natural (Last_Code);
end if;
Code := 0;
elsif Code = 63 then
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) * 3 + 3;
Code := 0;
elsif Code = 62 then
Offset_Backup := Offset;
Tools.Decode_Single (Input, Offset, Ignored (1), Code);
Verbatim_Length := Natural (Code) * 3 + 1;
Offset := Offset_Backup;
Code := 0;
else
Offset_Backup := Offset;
Verbatim_Length := (61 - Natural (Code)) * 4;
Tools.Decode_Double (Input, Offset, Ignored, Code);
Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2;
Offset := Offset_Backup;
Code := 0;
end if;
end Read_Code;
procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String)
is
Ignored : Tools.Base_64_Digit;
Output_Index : Natural := Output'First - 1;
begin
if Output'Length mod 3 = 1 then
Tools.Decode_Single
(Input, Offset, Output (Output_Index + 1), Ignored);
Output_Index := Output_Index + 1;
elsif Output'Length mod 3 = 2 then
Tools.Decode_Double
(Input, Offset,
Output (Output_Index + 1 .. Output_Index + 2), Ignored);
Output_Index := Output_Index + 2;
end if;
if Output_Index < Output'Last then
Tools.Decode
(Input, Offset, Output (Output_Index + 1 .. Output'Last));
end if;
end Read_Verbatim;
procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive)
is
Code : Tools.Base_64_Digit;
begin
for I in 1 .. Tools.Image_Length (Verbatim_Length) loop
Tools.Next_Digit (Input, Offset, Code);
end loop;
end Skip_Verbatim;
function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count is
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Run_Count : constant Natural
:= (Input_Length + Largest_Run - 1) / Largest_Run;
Last_Run_Size : constant Positive
:= Input_Length - (Run_Count - 1) * Largest_Run;
Last_Run_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Last_Run_Size > Largest_Single then 2 else 1);
begin
return Ada.Streams.Stream_Element_Count (Run_Count)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Last_Run_Size) + Last_Run_Header_Size;
end;
else
declare
Largest_Prefix : constant Natural
:= (case Input_Length mod 3 is
when 1 => 15 * 3 + 1,
when 2 => ((61 - Natural (Last_Code)) * 4 - 1) * 3 + 2,
when others => 0);
Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Largest_Prefix > 0 then 1 else 0);
Largest_Run : constant Positive := 64 * 3;
Prefix_Size : constant Natural
:= Natural'Min (Largest_Prefix, Input_Length);
Run_Count : constant Natural
:= (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run;
begin
if Run_Count > 0 then
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size)
+ Ada.Streams.Stream_Element_Count (Run_Count - 1)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Input_Length - Prefix_Size
- (Run_Count - 1) * Largest_Run)
+ 2;
else
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size);
end if;
end;
end if;
end Verbatim_Size;
procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is
begin
Output (Offset) := Tools.Image (Code);
Offset := Offset + 1;
end Write_Code;
procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Index : Positive := Input'First;
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Length, Last : Natural;
begin
while Index in Input'Range loop
Length := Positive'Min (Largest_Run, Input'Last + 1 - Index);
if Length > Largest_Single then
Write_Code (Output, Offset, 63);
Write_Code
(Output, Offset,
Tools.Base_64_Digit (Length - Largest_Single - 1));
else
Write_Code
(Output, Offset,
Tools.Base_64_Digit (63 - Length));
end if;
if Length mod 3 = 1 then
Tools.Encode_Single (Input (Index), 0, Output, Offset);
Index := Index + 1;
Length := Length - 1;
elsif Length mod 3 = 2 then
Tools.Encode_Double
(Input (Index .. Index + 1), 0, Output, Offset);
Index := Index + 2;
Length := Length - 2;
end if;
if Length > 0 then
Last := Index + Length - 1;
Tools.Encode (Input (Index .. Last), Output, Offset);
Index := Last + 1;
end if;
end loop;
end;
else
if Input'Length mod 3 = 1 then
declare
Extra_Blocks : constant Natural
:= Natural'Min (15, Input'Length / 3);
begin
Output (Offset) := Tools.Image (62);
Offset := Offset + 1;
Tools.Encode_Single
(Input (Index), Tools.Single_Byte_Padding (Extra_Blocks),
Output, Offset);
Index := Index + 1;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
elsif Input'Length mod 3 = 2 then
declare
Extra_Blocks : constant Natural := Natural'Min
(Input'Length / 3,
(61 - Natural (Last_Code)) * 4 - 1);
begin
Output (Offset)
:= Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4));
Offset := Offset + 1;
Tools.Encode_Double
(Input (Index .. Index + 1),
Tools.Double_Byte_Padding (Extra_Blocks mod 4),
Output, Offset);
Index := Index + 2;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
end if;
pragma Assert ((Input'Last + 1 - Index) mod 3 = 0);
while Index <= Input'Last loop
declare
Block_Count : constant Natural
:= Natural'Min (64, (Input'Last + 1 - Index) / 3);
begin
Output (Offset) := Tools.Image (63);
Output (Offset + 1)
:= Tools.Image (Tools.Base_64_Digit (Block_Count - 1));
Offset := Offset + 2;
Tools.Encode
(Input (Index .. Index + Block_Count * 3 - 1),
Output, Offset);
Index := Index + Block_Count * 3;
end;
end loop;
end if;
end Write_Verbatim;
end Natools.Smaz_Implementations.Base_64;
|
fix encoding issue with with multiblock
|
smaz_implementations-base_64: fix encoding issue with with multiblock
|
Ada
|
isc
|
faelys/natools
|
d04bba0b520a252ef6b4b6bf0aad761471eae304
|
src/portscan.adb
|
src/portscan.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Strings.Hash;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Parameters;
with Utilities;
package body PortScan is
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package UTL renames Utilities;
--------------------------------------------------------------------------------------------
-- port_hash
--------------------------------------------------------------------------------------------
function port_hash (key : HT.Text) return CON.Hash_Type is
begin
return Ada.Strings.Hash (HT.USS (key));
end port_hash;
--------------------------------------------------------------------------------------------
-- block_ekey
--------------------------------------------------------------------------------------------
function block_hash (key : port_index) return CON.Hash_Type is
preresult : constant CON.Hash_Type := CON.Hash_Type (key);
use type CON.Hash_Type;
begin
-- Equivalent to mod 128
return preresult and 2#1111111#;
end block_hash;
--------------------------------------------------------------------------------------------
-- block_ekey
--------------------------------------------------------------------------------------------
function block_ekey (left, right : port_index) return Boolean is
begin
return left = right;
end block_ekey;
--------------------------------------
-- "<" function for ranking_crate --
--------------------------------------
function "<" (L, R : queue_record) return Boolean is
begin
if L.reverse_score = R.reverse_score then
return R.ap_index > L.ap_index;
end if;
return L.reverse_score > R.reverse_score;
end "<";
--------------------------------------------------------------------------------------------
-- get_bucket
--------------------------------------------------------------------------------------------
function get_bucket (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "XX";
end if;
return all_ports (id).bucket;
end get_bucket;
--------------------------------------------------------------------------------------------
-- get_port_variant #1
--------------------------------------------------------------------------------------------
function get_port_variant (PR : port_record) return String
is
use type portkey_crate.Cursor;
begin
if PR.key_cursor = portkey_crate.No_Element then
return "get_port_variant: invalid key_cursor";
end if;
return HT.USS (portkey_crate.Key (PR.key_cursor));
end get_port_variant;
--------------------------------------------------------------------------------------------
-- get_port_variant #2
--------------------------------------------------------------------------------------------
function get_port_variant (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "Invalid port ID";
end if;
return get_port_variant (all_ports (id));
end get_port_variant;
--------------------------------------------------------------------------------------------
-- ignore_reason
--------------------------------------------------------------------------------------------
function ignore_reason (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "Invalid port ID";
end if;
return HT.USS (all_ports (id).ignore_reason);
end ignore_reason;
--------------------------------------------------------------------------------------------
-- valid_port_id
--------------------------------------------------------------------------------------------
function valid_port_id (id : port_id) return Boolean is
begin
return id /= port_match_failed;
end valid_port_id;
--------------------------------------------------------------------------------------------
-- wipe_make_queue
--------------------------------------------------------------------------------------------
procedure wipe_make_queue is
begin
for j in scanners'Range loop
make_queue (j).Clear;
end loop;
end wipe_make_queue;
--------------------------------------------------------------------------------------------
-- reset_ports_tree
--------------------------------------------------------------------------------------------
procedure reset_ports_tree is
begin
for k in dim_all_ports'Range loop
declare
rec : port_record renames all_ports (k);
begin
rec.sequence_id := 0;
rec.key_cursor := portkey_crate.No_Element;
rec.ignore_reason := HT.blank;
rec.pkgversion := HT.blank;
rec.port_variant := HT.blank;
rec.port_namebase := HT.blank;
rec.bucket := "00";
rec.unkind_custom := False;
rec.ignored := False;
rec.scanned := False;
rec.rev_scanned := False;
rec.unlist_failed := False;
rec.work_locked := False;
rec.scan_locked := False;
rec.use_procfs := False;
rec.reverse_score := 0;
rec.run_deps.Clear;
rec.blocked_by.Clear;
rec.blocks.Clear;
rec.all_reverse.Clear;
rec.options.Clear;
rec.subpackages.Clear;
end;
end loop;
ports_keys.Clear;
rank_queue.Clear;
lot_number := 1;
lot_counter := 0;
last_port := 0;
prescanned := False;
wipe_make_queue;
for m in scanners'Range loop
mq_progress (m) := 0;
end loop;
end reset_ports_tree;
--------------------------------------------------------------------------------------------
-- queue_is_empty
--------------------------------------------------------------------------------------------
function queue_is_empty return Boolean is
begin
return rank_queue.Is_Empty;
end queue_is_empty;
--------------------------------------------------------------------------------------------
-- queue_is_empty
--------------------------------------------------------------------------------------------
function original_queue_size return Natural is
begin
return Natural (original_queue_len);
end original_queue_size;
--------------------------------------------------------------------------------------------
-- queue_length
--------------------------------------------------------------------------------------------
function queue_length return Integer is
begin
return Integer (rank_queue.Length);
end queue_length;
--------------------------------------------------------------------------------------------
-- calculate_package_name
--------------------------------------------------------------------------------------------
function calculate_package_name (id : port_id; subpackage : String) return String
is
namebase : constant String := HT.USS (all_ports (id).port_namebase);
variant : constant String := HT.USS (all_ports (id).port_variant);
pkgversion : constant String := HT.USS (all_ports (id).pkgversion);
begin
return namebase & "-" & subpackage & "-" & variant & "-" & pkgversion;
end calculate_package_name;
--------------------------------------------------------------------------------------------
-- convert_depend_origin_to_portkey
--------------------------------------------------------------------------------------------
function convert_depend_origin_to_portkey (origin : String) return String
is
-- expected format: namebase:subpackage:variant
numcolons : Natural := HT.count_char (origin, LAT.Colon);
begin
if numcolons < 2 then
return "error";
end if;
declare
namebase : String := HT.specific_field (origin, 1, ":");
variant : String := HT.specific_field (origin, 3, ":");
begin
return namebase & LAT.Colon & variant;
end;
end convert_depend_origin_to_portkey;
--------------------------------------------------------------------------------------------
-- subpackage_from_pkgname
--------------------------------------------------------------------------------------------
function subpackage_from_pkgname (pkgname : String) return String
is
-- expected format: namebase-subpackage-variant-version.tzst
-- support namebase-subpackage-variant too
numcolons : Natural := HT.count_char (pkgname, LAT.Hyphen);
begin
if numcolons < 3 then
return "error";
end if;
return HT.tail (HT.head (HT.head (pkgname, "-"), "-"), "-");
end subpackage_from_pkgname;
--------------------------------------------------------------------------------------------
-- scan_progress
--------------------------------------------------------------------------------------------
function scan_progress return String
is
type percent is delta 0.01 digits 5;
complete : port_index := 0;
pc : percent;
maximum : Float := Float (last_port + 1);
begin
for k in scanners'Range loop
complete := complete + mq_progress (k);
end loop;
pc := percent (100.0 * Float (complete) / maximum);
return " progress:" & pc'Img & "% " & LAT.CR;
end scan_progress;
--------------------------------------------------------------------------------------------
-- insert_into_portlist
--------------------------------------------------------------------------------------------
procedure insert_into_portlist (port_variant : String)
is
pv_text : HT.Text := HT.SUS (port_variant);
begin
if not portlist.Contains (pv_text) then
portlist.Append (pv_text);
dupelist.Append (pv_text);
end if;
end insert_into_portlist;
--------------------------------------------------------------------------------------------
-- jail_env_port_specified
--------------------------------------------------------------------------------------------
function jail_env_port_specified return Boolean is
begin
return
portlist.Contains (HT.SUS (default_compiler & ":standard")) or else
portlist.Contains (HT.SUS ("binutils:ravensys"));
end jail_env_port_specified;
--------------------------------------------------------------------------------------------
-- requires_procfs
--------------------------------------------------------------------------------------------
function requires_procfs (id : port_id) return Boolean is
begin
return all_ports (id).use_procfs;
end requires_procfs;
--------------------------------------------------------------------------------------------
-- build_request_length
--------------------------------------------------------------------------------------------
function build_request_length return Integer is
begin
return Integer (dupelist.Length);
end build_request_length;
--------------------------------------------------------------------------------------------
-- get_buildsheet_from_origin_list
--------------------------------------------------------------------------------------------
function get_buildsheet_from_origin_list (index : Positive) return String
is
procedure search (position : string_crate.Cursor);
conspiracy : constant String := HT.USS (Parameters.configuration.dir_conspiracy);
unkindness : constant String := HT.USS (Parameters.configuration.dir_unkindness);
counter : Natural := 0;
answer : HT.Text;
procedure search (position : string_crate.Cursor) is
begin
counter := counter + 1;
if counter = index then
declare
namebase : String := HT.part_1 (HT.USS (string_crate.Element (position)), ":");
bsheetname : String := "/bucket_" & UTL.bucket (namebase) & "/" & namebase;
begin
if DIR.Exists (unkindness & bsheetname) then
answer := HT.SUS (unkindness & bsheetname);
else
answer := HT.SUS (conspiracy & bsheetname);
end if;
end;
end if;
end search;
begin
dupelist.Iterate (search'Access);
return HT.USS (answer);
end get_buildsheet_from_origin_list;
end PortScan;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Strings.Hash;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Parameters;
with Utilities;
package body PortScan is
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package UTL renames Utilities;
--------------------------------------------------------------------------------------------
-- port_hash
--------------------------------------------------------------------------------------------
function port_hash (key : HT.Text) return CON.Hash_Type is
begin
return Ada.Strings.Hash (HT.USS (key));
end port_hash;
--------------------------------------------------------------------------------------------
-- block_ekey
--------------------------------------------------------------------------------------------
function block_hash (key : port_index) return CON.Hash_Type is
preresult : constant CON.Hash_Type := CON.Hash_Type (key);
use type CON.Hash_Type;
begin
-- Equivalent to mod 128
return preresult and 2#1111111#;
end block_hash;
--------------------------------------------------------------------------------------------
-- block_ekey
--------------------------------------------------------------------------------------------
function block_ekey (left, right : port_index) return Boolean is
begin
return left = right;
end block_ekey;
--------------------------------------
-- "<" function for ranking_crate --
--------------------------------------
function "<" (L, R : queue_record) return Boolean is
begin
if L.reverse_score = R.reverse_score then
return R.ap_index > L.ap_index;
end if;
return L.reverse_score > R.reverse_score;
end "<";
--------------------------------------------------------------------------------------------
-- get_bucket
--------------------------------------------------------------------------------------------
function get_bucket (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "XX";
end if;
return all_ports (id).bucket;
end get_bucket;
--------------------------------------------------------------------------------------------
-- get_port_variant #1
--------------------------------------------------------------------------------------------
function get_port_variant (PR : port_record) return String
is
use type portkey_crate.Cursor;
begin
if PR.key_cursor = portkey_crate.No_Element then
return "get_port_variant: invalid key_cursor";
end if;
return HT.USS (portkey_crate.Key (PR.key_cursor));
end get_port_variant;
--------------------------------------------------------------------------------------------
-- get_port_variant #2
--------------------------------------------------------------------------------------------
function get_port_variant (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "Invalid port ID";
end if;
return get_port_variant (all_ports (id));
end get_port_variant;
--------------------------------------------------------------------------------------------
-- ignore_reason
--------------------------------------------------------------------------------------------
function ignore_reason (id : port_id) return String is
begin
if id = port_match_failed or else id > last_port then
return "Invalid port ID";
end if;
return HT.USS (all_ports (id).ignore_reason);
end ignore_reason;
--------------------------------------------------------------------------------------------
-- valid_port_id
--------------------------------------------------------------------------------------------
function valid_port_id (id : port_id) return Boolean is
begin
return id /= port_match_failed;
end valid_port_id;
--------------------------------------------------------------------------------------------
-- wipe_make_queue
--------------------------------------------------------------------------------------------
procedure wipe_make_queue is
begin
for j in scanners'Range loop
make_queue (j).Clear;
end loop;
end wipe_make_queue;
--------------------------------------------------------------------------------------------
-- reset_ports_tree
--------------------------------------------------------------------------------------------
procedure reset_ports_tree is
begin
for k in dim_all_ports'Range loop
declare
rec : port_record renames all_ports (k);
begin
rec.sequence_id := 0;
rec.key_cursor := portkey_crate.No_Element;
rec.ignore_reason := HT.blank;
rec.pkgversion := HT.blank;
rec.port_variant := HT.blank;
rec.port_namebase := HT.blank;
rec.bucket := "00";
rec.unkind_custom := False;
rec.ignored := False;
rec.scanned := False;
rec.rev_scanned := False;
rec.unlist_failed := False;
rec.work_locked := False;
rec.scan_locked := False;
rec.use_procfs := False;
rec.reverse_score := 0;
rec.run_deps.Clear;
rec.blocked_by.Clear;
rec.blocks.Clear;
rec.all_reverse.Clear;
rec.options.Clear;
rec.subpackages.Clear;
end;
end loop;
ports_keys.Clear;
rank_queue.Clear;
lot_number := 1;
lot_counter := 0;
last_port := 0;
prescanned := False;
wipe_make_queue;
for m in scanners'Range loop
mq_progress (m) := 0;
end loop;
end reset_ports_tree;
--------------------------------------------------------------------------------------------
-- queue_is_empty
--------------------------------------------------------------------------------------------
function queue_is_empty return Boolean is
begin
return rank_queue.Is_Empty;
end queue_is_empty;
--------------------------------------------------------------------------------------------
-- queue_is_empty
--------------------------------------------------------------------------------------------
function original_queue_size return Natural is
begin
return Natural (original_queue_len);
end original_queue_size;
--------------------------------------------------------------------------------------------
-- queue_length
--------------------------------------------------------------------------------------------
function queue_length return Integer is
begin
return Integer (rank_queue.Length);
end queue_length;
--------------------------------------------------------------------------------------------
-- calculate_package_name
--------------------------------------------------------------------------------------------
function calculate_package_name (id : port_id; subpackage : String) return String
is
namebase : constant String := HT.USS (all_ports (id).port_namebase);
variant : constant String := HT.USS (all_ports (id).port_variant);
pkgversion : constant String := HT.USS (all_ports (id).pkgversion);
begin
return namebase & "-" & subpackage & "-" & variant & "-" & pkgversion;
end calculate_package_name;
--------------------------------------------------------------------------------------------
-- convert_depend_origin_to_portkey
--------------------------------------------------------------------------------------------
function convert_depend_origin_to_portkey (origin : String) return String
is
-- expected format: namebase:subpackage:variant
numcolons : Natural := HT.count_char (origin, LAT.Colon);
begin
if numcolons < 2 then
return "error";
end if;
declare
namebase : String := HT.specific_field (origin, 1, ":");
variant : String := HT.specific_field (origin, 3, ":");
begin
return namebase & LAT.Colon & variant;
end;
end convert_depend_origin_to_portkey;
--------------------------------------------------------------------------------------------
-- subpackage_from_pkgname
--------------------------------------------------------------------------------------------
function subpackage_from_pkgname (pkgname : String) return String
is
-- expected format: namebase-subpackage-variant-version.tzst
-- support namebase-subpackage-variant too
numcolons : Natural := HT.count_char (pkgname, LAT.Hyphen);
begin
if numcolons < 3 then
return "error";
end if;
return HT.tail (HT.head (HT.head (pkgname, "-"), "-"), "-");
end subpackage_from_pkgname;
--------------------------------------------------------------------------------------------
-- scan_progress
--------------------------------------------------------------------------------------------
function scan_progress return String
is
type percent is delta 0.01 digits 5;
complete : port_index := 0;
pc : percent;
maximum : Float := Float (last_port + 1);
begin
for k in scanners'Range loop
complete := complete + mq_progress (k);
end loop;
pc := percent (100.0 * Float (complete) / maximum);
return " progress:" & pc'Img & "% " & LAT.CR;
end scan_progress;
--------------------------------------------------------------------------------------------
-- insert_into_portlist
--------------------------------------------------------------------------------------------
procedure insert_into_portlist (port_variant : String)
is
pv_text : HT.Text := HT.SUS (port_variant);
begin
if not portlist.Contains (pv_text) then
portlist.Append (pv_text);
dupelist.Append (pv_text);
end if;
end insert_into_portlist;
--------------------------------------------------------------------------------------------
-- jail_env_port_specified
--------------------------------------------------------------------------------------------
function jail_env_port_specified return Boolean is
begin
return
portlist.Contains (HT.SUS (default_compiler & ":standard")) or else
portlist.Contains (HT.SUS ("binutils:ravensys"));
end jail_env_port_specified;
--------------------------------------------------------------------------------------------
-- requires_procfs
--------------------------------------------------------------------------------------------
function requires_procfs (id : port_id) return Boolean is
begin
return all_ports (id).use_procfs;
end requires_procfs;
--------------------------------------------------------------------------------------------
-- build_request_length
--------------------------------------------------------------------------------------------
function build_request_length return Integer is
begin
return Integer (dupelist.Length);
end build_request_length;
--------------------------------------------------------------------------------------------
-- get_buildsheet_from_origin_list
--------------------------------------------------------------------------------------------
function get_buildsheet_from_origin_list (index : Positive) return String
is
procedure search (position : string_crate.Cursor);
conspiracy : constant String := HT.USS (Parameters.configuration.dir_conspiracy);
unkindness : constant String := HT.USS (Parameters.configuration.dir_profile) &
"/unkindness";
counter : Natural := 0;
answer : HT.Text;
procedure search (position : string_crate.Cursor) is
begin
counter := counter + 1;
if counter = index then
declare
namebase : String := HT.part_1 (HT.USS (string_crate.Element (position)), ":");
bsheetname : String := "/bucket_" & UTL.bucket (namebase) & "/" & namebase;
begin
if DIR.Exists (unkindness & bsheetname) then
answer := HT.SUS (unkindness & bsheetname);
else
answer := HT.SUS (conspiracy & bsheetname);
end if;
end;
end if;
end search;
begin
dupelist.Iterate (search'Access);
return HT.USS (answer);
end get_buildsheet_from_origin_list;
end PortScan;
|
Fix set-options command for custom ports
|
Fix set-options command for custom ports
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
e7587794233a5fe90cd681239bb9d3ae2330f4d3
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
Implement the Set_Signature operation and setup the file status flags accordingly
|
Implement the Set_Signature operation and setup the file status flags accordingly
|
Ada
|
apache-2.0
|
stcarrez/babel
|
604071a20bf4a3c738843c8b00ee27720c556da7
|
src/babel-files.ads
|
src/babel-files.ads
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Path : in String;
Element : in File) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Path : in String;
Name : in String) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
private
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type File_Type is access all File;
type Directory_Type is access all Directory;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Path : in String;
Element : in File) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Path : in String;
Name : in String) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
private
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type File_Type is access all File;
type Directory_Type is access all Directory;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
Add a Create function to the File_Container to create a new directory
|
Add a Create function to the File_Container to create a new directory
|
Ada
|
apache-2.0
|
stcarrez/babel
|
6c08a2e9c1dad62e318a568134d714a15d3fa3fe
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Document the permission
|
Document the permission
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
4c926651f15da7eb44737bdfe757583572805293
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "02";
copyright_years : constant String := "2015-2017";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "03";
copyright_years : constant String := "2015-2017";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
Bump version
|
Bump version
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
550f60d8523994291fd5c64bdc31aaf0673a0e76
|
regtests/security-oauth-servers-tests.ads
|
regtests/security-oauth-servers-tests.ads
|
-----------------------------------------------------------------------
-- Security-oauth-servers-tests - Unit tests for server side OAuth
-- 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 Security.OAuth.Servers.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the application manager.
procedure Test_Application_Manager (T : in out Test);
-- Test the user registration and verification.
procedure Test_User_Verify (T : in out Test);
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
procedure Test_Token_Password (T : in out Test);
-- Test the access token validation with invalid tokens (bad formed).
procedure Test_Bad_Token (T : in out Test);
end Security.OAuth.Servers.Tests;
|
-----------------------------------------------------------------------
-- Security-oauth-servers-tests - Unit tests for server side OAuth
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Security.OAuth.Servers.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the application manager.
procedure Test_Application_Manager (T : in out Test);
-- Test the user registration and verification.
procedure Test_User_Verify (T : in out Test);
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
procedure Test_Token_Password (T : in out Test);
-- Test the access token validation with invalid tokens (bad formed).
procedure Test_Bad_Token (T : in out Test);
-- Test the loading configuration files for the File_Registry.
procedure Test_Load_Registry (T : in out Test);
end Security.OAuth.Servers.Tests;
|
Declare the Test_Load_Registry procedure to test the File_Registry
|
Declare the Test_Load_Registry procedure to test the File_Registry
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
b3823f3f2538e6c7d988d51fa1d923253ecba4eb
|
src/wiki-parsers-textile.adb
|
src/wiki-parsers-textile.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Textile is
use Wiki.Helpers;
use Wiki.Buffers;
use type Wiki.Nodes.Node_Kind;
function Get_Header_Level (Text : in Wiki.Strings.WString) return Natural is
begin
if Text'Length <= 4 or else Text (Text'First) /= 'h' then
return 0;
end if;
if Text (Text'First + 2) /= '.' or not Is_Space (Text (Text'First + 3)) then
return 0;
end if;
case Text (Text'First + 1) is
when '1' =>
return 1;
when '2' =>
return 2;
when '3' =>
return 3;
when '4' =>
return 4;
when '5' =>
return 5;
when others =>
return 0;
end case;
end Get_Header_Level;
-- ------------------------------
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
-- ------------------------------
procedure Parse_Header (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Level : in Positive) is
begin
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Parser.Header_Level := Level;
Push_Block (Parser, Nodes.N_HEADER);
declare
Pos : Natural := From;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if not Wiki.Helpers.Is_Space_Or_Newline (Buffer.Content (Pos)) then
Common.Append (Parser.Text, Buffer, Pos);
Text := null;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end;
end Parse_Header;
-- ------------------------------
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path!:http-link
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
Find (Block, Pos, '!');
if Block = null then
Common.Parse_Text (Parser, Text, From);
return;
end if;
declare
Link : Wiki.Strings.BString (128);
Title : Wiki.Strings.BString (128);
C : Wiki.Strings.WChar := Wiki.Html_Parser.NUL;
begin
Block := Text;
Pos := From;
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when C = '(' or C = '!';
Append (Link, C);
Next (Block, Pos);
end loop;
if C = '(' then
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when C = ')' or C = '!';
Append (Title, C);
Next (Block, Pos);
end loop;
if C /= ')' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Title),
Parser.Attributes);
end if;
end;
end Parse_Image;
-- ------------------------------
-- Parse an external link:
-- Example:
-- "title":http-link
-- ------------------------------
procedure Parse_Link (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
Http : constant Wiki.Strings.WString := ":http";
begin
Next (Block, Pos);
Find (Block, Pos, '"');
if Block = null then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
for Expect of Http loop
if Block = null or else Block.Content (Pos) /= Expect then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
end loop;
declare
Title : Wiki.Strings.BString (128);
Link : Wiki.Strings.BString (128);
C : Wiki.Strings.WChar;
begin
Block := Text;
Pos := From;
Next (Block, Pos);
while Block.Content (Pos) /= '"' loop
Append (Title, Block.Content (Pos));
Next (Block, Pos);
end loop;
-- Skip the ":
Next (Block, Pos);
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when Wiki.Helpers.Is_Space_Or_Newline (C);
Append (Link, C);
Next (Block, Pos);
end loop;
Text := Block;
From := Pos;
Flush_Text (Parser);
Wiki.Attributes.Clear (Parser.Attributes);
Parser.Line_Pos := Pos;
Parser.Empty_Line := False;
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Append (Parser.Attributes, NAME_ATTR, Title);
Wiki.Attributes.Append (Parser.Attributes, HREF_ATTR, Link);
Parser.Context.Filters.Add_Link (Parser.Document,
Wiki.Strings.To_WString (Title),
Parser.Attributes);
end if;
end;
end Parse_Link;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Level : Natural;
begin
-- Feed the HTML parser if there are some pending state.
if not Wiki.Html_Parser.Is_Empty (Parser.Html) then
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False);
if Buffer = null then
return;
end if;
end if;
if Parser.Pre_Tag_Counter > 0 then
Common.Parse_Html_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
end if;
if Parser.Current_Node = Nodes.N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when 'h' =>
Level := Get_Header_Level (Buffer.Content (1 .. Buffer.Last));
if Level > 0 and Level <= 6 then
Pos := 4;
Parse_Header (Parser, Buffer, Pos, Level);
return;
end if;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
if Common.Is_List (Buffer, Pos) then
Common.Parse_List (Parser, Buffer, Pos);
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, Nodes.N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when ';' =>
Common.Parse_Definition (Parser, Buffer, Pos);
return;
when ':' =>
if Parser.Current_Node = Nodes.N_DEFINITION then
Next (Buffer, Pos);
Common.Skip_Spaces (Buffer, Pos);
end if;
when others =>
if Parser.Current_Node /= Nodes.N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, Nodes.N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '*' =>
Parse_Format (Parser, Buffer, Pos, '*', Wiki.BOLD);
exit Main when Buffer = null;
when '@' =>
Parse_Format (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '_' =>
Parse_Format (Parser, Buffer, Pos, '_', Wiki.EMPHASIS);
exit Main when Buffer = null;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '?' =>
Parse_Format_Double (Parser, Buffer, Pos, '?', Wiki.CITE);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Template (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '"' =>
Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '!' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when CR | LF =>
Append (Parser.Text, ' ');
Pos := Pos + 1;
when '<' =>
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True);
exit Main when Buffer = null;
when '&' =>
Common.Parse_Entity (Parser, Buffer, Pos);
exit Main when Buffer = null;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Textile;
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Textile is
use Wiki.Helpers;
use Wiki.Buffers;
use type Wiki.Nodes.Node_Kind;
function Get_Header_Level (Text : in Wiki.Strings.WString) return Natural is
begin
if Text'Length <= 4 or else Text (Text'First) /= 'h' then
return 0;
end if;
if Text (Text'First + 2) /= '.' or not Is_Space (Text (Text'First + 3)) then
return 0;
end if;
case Text (Text'First + 1) is
when '1' =>
return 1;
when '2' =>
return 2;
when '3' =>
return 3;
when '4' =>
return 4;
when '5' =>
return 5;
when others =>
return 0;
end case;
end Get_Header_Level;
-- ------------------------------
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
-- ------------------------------
procedure Parse_Header (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Level : in Positive) is
begin
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Parser.Header_Level := Level;
Push_Block (Parser, Nodes.N_HEADER);
declare
Pos : Natural := From;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if not Wiki.Helpers.Is_Space_Or_Newline (Buffer.Content (Pos)) then
Common.Append (Parser.Text, Buffer, Pos);
Text := null;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end;
end Parse_Header;
-- ------------------------------
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path!:http-link
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
Find (Block, Pos, '!');
if Block = null then
Common.Parse_Text (Parser, Text, From);
return;
end if;
declare
Link : Wiki.Strings.BString (128);
Title : Wiki.Strings.BString (128);
C : Wiki.Strings.WChar := Wiki.Html_Parser.NUL;
begin
Block := Text;
Pos := From;
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when C = '(' or C = '!';
Append (Link, C);
Next (Block, Pos);
end loop;
if C = '(' then
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when C = ')' or C = '!';
Append (Title, C);
Next (Block, Pos);
end loop;
if C /= ')' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Title),
Parser.Attributes);
end if;
end;
end Parse_Image;
-- ------------------------------
-- Parse an external link:
-- Example:
-- "title":http-link
-- ------------------------------
procedure Parse_Link (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
Http : constant Wiki.Strings.WString := ":http";
begin
Next (Block, Pos);
Find (Block, Pos, '"');
if Block = null then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
for Expect of Http loop
if Block = null or else Block.Content (Pos) /= Expect then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
end loop;
declare
Title : Wiki.Strings.BString (128);
Link : Wiki.Strings.BString (128);
C : Wiki.Strings.WChar;
begin
Block := Text;
Pos := From;
Next (Block, Pos);
while Block.Content (Pos) /= '"' loop
Append (Title, Block.Content (Pos));
Next (Block, Pos);
end loop;
-- Skip the ":
Next (Block, Pos);
Next (Block, Pos);
while Block /= null loop
C := Block.Content (Pos);
exit when Wiki.Helpers.Is_Space_Or_Newline (C);
Append (Link, C);
Next (Block, Pos);
end loop;
Text := Block;
From := Pos;
Flush_Text (Parser);
Wiki.Attributes.Clear (Parser.Attributes);
Parser.Line_Pos := Pos;
Parser.Empty_Line := False;
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Append (Parser.Attributes, NAME_ATTR, Title);
Wiki.Attributes.Append (Parser.Attributes, HREF_ATTR, Link);
Parser.Context.Filters.Add_Link (Parser.Document,
Wiki.Strings.To_WString (Title),
Parser.Attributes);
end if;
end;
end Parse_Link;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Level : Natural;
begin
-- Feed the HTML parser if there are some pending state.
if not Wiki.Html_Parser.Is_Empty (Parser.Html) then
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False);
if Buffer = null then
return;
end if;
end if;
if Parser.Pre_Tag_Counter > 0 then
Common.Parse_Html_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
end if;
if Parser.Current_Node = Nodes.N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when 'h' =>
Level := Get_Header_Level (Buffer.Content (1 .. Buffer.Last));
if Level > 0 and Level <= 6 then
Pos := 4;
Parse_Header (Parser, Buffer, Pos, Level);
return;
end if;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
if Common.Is_List (Buffer, Pos) then
Common.Parse_List (Parser, Buffer, Pos);
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, Nodes.N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when ';' =>
Common.Parse_Definition (Parser, Buffer, Pos);
return;
when ':' =>
if Parser.Current_Node = Nodes.N_DEFINITION then
Next (Buffer, Pos);
Common.Skip_Spaces (Buffer, Pos);
end if;
when others =>
if Parser.Current_Node /= Nodes.N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, Nodes.N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '*' =>
if Parser.Format (CODE) then
Append (Parser.Text, C);
Pos := Pos + 1;
else
Parse_Format (Parser, Buffer, Pos, '*', Wiki.BOLD);
exit Main when Buffer = null;
end if;
when '@' =>
Parse_Format (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '_' =>
if Parser.Format (CODE) then
Append (Parser.Text, C);
Pos := Pos + 1;
else
Parse_Format (Parser, Buffer, Pos, '_', Wiki.EMPHASIS);
exit Main when Buffer = null;
end if;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '?' =>
Parse_Format_Double (Parser, Buffer, Pos, '?', Wiki.CITE);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Template (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '"' =>
Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '!' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when CR | LF =>
Append (Parser.Text, ' ');
Pos := Pos + 1;
when '<' =>
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True);
exit Main when Buffer = null;
when '&' =>
Common.Parse_Entity (Parser, Buffer, Pos);
exit Main when Buffer = null;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Textile;
|
Update textile parsing rules
|
Update textile parsing rules
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
82e66ec6000597fed52e2dcd4c6863e6936a6c60
|
src/wiki-filters-html.ads
|
src/wiki-filters-html.ads
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML 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.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
use Wiki.Nodes;
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Filter_Type);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Document : in out Html_Filter_Type);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag_Type) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag_Type);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML 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.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
use Wiki.Nodes;
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag_Type) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag_Type);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
Add Document parameter to Finish and Flush_Stack
|
Add Document parameter to Finish and Flush_Stack
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
79a3d07b8975d52da038879b9f02fcd28df944be
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Events.Action_Method;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a0f07b6d8dddd72934c8d5fda1a9c9056f298e93
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact 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.
overriding
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.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact 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.
overriding
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.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the <<Version>> stereotype
|
Add the <<Version>> stereotype
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
c915c301b975ab07cf5ff192aa67680351601a81
|
src/wiki-filters-html.adb
|
src/wiki-filters-html.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 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 Wiki.Helpers;
package body Wiki.Filters.Html is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
when N_TOC_DISPLAY =>
return;
when N_NEWLINE =>
Filter_Type (Filter).Add_Node (Document, Kind);
return;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
elsif not Filter.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
Filter.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Wiki.Helpers.Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 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.Helpers;
package body Wiki.Filters.Html is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
when N_TOC_DISPLAY =>
return;
when N_NEWLINE =>
Filter_Type (Filter).Add_Node (Document, Kind);
return;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Wiki.Helpers.Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit;
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
Fix HTML filter: we can assume that the parse will close hr/br/meta/img tags if necessary
|
Fix HTML filter: we can assume that the parse will close hr/br/meta/img tags if necessary
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
778856fe1e2da0241727fe6dd7f2b63b76f98563
|
src/wiki-parsers-textile.adb
|
src/wiki-parsers-textile.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
package body Wiki.Parsers.Textile is
use Wiki.Helpers;
use Wiki.Nodes;
-- ------------------------------
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
-- ------------------------------
procedure Parse_Header (P : in out Parser;
Token : in Wiki.Strings.WChar) is
procedure Add_Header (Content : in Wiki.Strings.WString);
C : Wiki.Strings.WChar;
C2 : Wiki.Strings.WChar;
Level : Integer := 1;
procedure Add_Header (Content : in Wiki.Strings.WString) is
Last : Natural := Content'Last;
Ignore_Token : Boolean := True;
Seen_Token : Boolean := False;
begin
-- Remove the spaces and '=' at end of header string.
while Last > Content'First loop
if Content (Last) = Token then
exit when not Ignore_Token;
Seen_Token := True;
elsif Content (Last) = ' ' or Content (Last) = HT then
Ignore_Token := not Seen_Token;
else
exit;
end if;
Last := Last - 1;
end loop;
P.Context.Filters.Add_Header (P.Document, Content (Content'First .. Last), Level);
end Add_Header;
procedure Add_Header is
new Wiki.Strings.Wide_Wide_Builders.Get (Add_Header);
begin
if not P.Empty_Line then
Parse_Text (P, Token);
return;
end if;
Peek (P, C);
case C is
when '1' =>
Level := 1;
when '2' =>
Level := 2;
when '3' =>
Level := 3;
when '4' =>
Level := 4;
when '5' =>
Level := 5;
when others =>
Parse_Text (P, Token);
Parse_Text (P, C);
return;
end case;
Peek (P, C2);
if C2 /= '.' then
Parse_Text (P, Token);
Parse_Text (P, C);
Parse_Text (P, C2);
return;
end if;
-- Ignore spaces after the hN. sequence
Peek (P, C);
while C = ' ' or C = HT loop
Peek (P, C);
end loop;
Flush_Text (P);
Flush_List (P);
loop
Append (P.Text, C);
Peek (P, C);
exit when C = LF or C = CR;
end loop;
if not P.Context.Is_Hidden then
Add_Header (P.Text);
end if;
P.Empty_Line := True;
P.In_Paragraph := False;
Clear (P.Text);
end Parse_Header;
-- ------------------------------
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path!:http-link
-- ------------------------------
procedure Parse_Image (P : in out Parser;
Token : in Wiki.Strings.WChar) is
Pos : Natural := P.Line_Pos + 1;
Last : Natural;
C : Wiki.Strings.WChar;
begin
Last := Wiki.Strings.Index (P.Line, '!', Pos);
if Last = 0 then
Append (P.Text, Token);
return;
end if;
declare
Title : Wiki.Strings.UString;
Link : Wiki.Strings.UString;
Title_Pos : Natural;
Last_Pos : Natural;
begin
Title_Pos := Wiki.Strings.Index (P.Line, '(', Pos);
if Title_Pos = 0 then
Last_Pos := Last;
else
Last_Pos := Title_Pos;
end if;
while Pos < Last_Pos loop
Wiki.Strings.Append (Link, Wiki.Strings.Element (P.Line, Pos));
Pos := Pos + 1;
end loop;
if Title_Pos > 0 then
Title_Pos := Title_Pos + 1;
while Title_Pos < Last - 1 loop
Wiki.Strings.Append (Title, Wiki.Strings.Element (P.Line, Title_Pos));
Title_Pos := Title_Pos + 1;
end loop;
end if;
Flush_Text (P);
P.Line_Pos := Last;
if not P.Context.Is_Hidden then
Wiki.Attributes.Clear (P.Attributes);
Wiki.Attributes.Append (P.Attributes, "src", Link);
P.Context.Filters.Add_Image (P.Document, Wiki.Strings.To_WString (Title),
P.Attributes);
end if;
end;
end Parse_Image;
-- Parse an external link:
-- Example:
-- "title":http-link
procedure Parse_Link (P : in out Parser;
Token : in Wiki.Strings.WChar) is
Pos : Natural := P.Line_Pos;
Next : Natural := Wiki.Strings.Index (P.Line, Token, Pos);
C : Wiki.Strings.WChar;
begin
if Next = 0 or Next = P.Line_Length then
Append (P.Text, Token);
return;
end if;
C := Wiki.Strings.Element(P.Line, Next + 1);
if C /= ':' then
Append (P.Text, Token);
return;
end if;
Flush_Text (P);
Wiki.Attributes.Clear (P.Attributes);
P.Empty_Line := False;
if not P.Context.Is_Hidden then
declare
Link : constant Strings.WString := Attributes.Get_Attribute (P.Attributes, HREF_ATTR);
Name : constant Strings.WString := Attributes.Get_Attribute (P.Attributes, NAME_ATTR);
begin
P.Context.Filters.Add_Link (P.Document, Name, P.Attributes);
end;
end if;
end Parse_Link;
-- ------------------------------
-- Parse a bold sequence or a list.
-- Example:
-- *name* (bold)
-- * item (list)
-- ------------------------------
procedure Parse_Bold_Or_List (P : in out Parser;
Token : in Wiki.Strings.WChar) is
C : Wiki.Strings.WChar;
begin
Peek (P, C);
if P.Empty_Line and C = ' ' then
Put_Back (P, C);
Common.Parse_List (P, Token);
return;
end if;
Put_Back (P, C);
Toggle_Format (P, BOLD);
end Parse_Bold_Or_List;
-- Parse a markdown table/column.
-- Example:
-- | col1 | col2 | ... | colN |
procedure Parse_Table (P : in out Parser;
Token : in Wiki.Strings.WChar) is
begin
null;
end Parse_Table;
procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser;
Token : in Wiki.Strings.WChar) is
begin
null;
end Parse_Deleted_Or_Horizontal_Rule;
end Wiki.Parsers.Textile;
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
package body Wiki.Parsers.Textile is
use Wiki.Helpers;
use Wiki.Nodes;
-- ------------------------------
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
-- ------------------------------
procedure Parse_Header (P : in out Parser;
Token : in Wiki.Strings.WChar) is
procedure Add_Header (Content : in Wiki.Strings.WString);
C : Wiki.Strings.WChar;
C2 : Wiki.Strings.WChar;
Level : Integer := 1;
procedure Add_Header (Content : in Wiki.Strings.WString) is
Last : Natural := Content'Last;
Ignore_Token : Boolean := True;
Seen_Token : Boolean := False;
begin
-- Remove the spaces and '=' at end of header string.
while Last > Content'First loop
if Content (Last) = Token then
exit when not Ignore_Token;
Seen_Token := True;
elsif Content (Last) = ' ' or Content (Last) = HT then
Ignore_Token := not Seen_Token;
else
exit;
end if;
Last := Last - 1;
end loop;
P.Context.Filters.Add_Header (P.Document, Content (Content'First .. Last), Level);
end Add_Header;
procedure Add_Header is
new Wiki.Strings.Wide_Wide_Builders.Get (Add_Header);
begin
if not P.Empty_Line then
Parse_Text (P, Token);
return;
end if;
Peek (P, C);
case C is
when '1' =>
Level := 1;
when '2' =>
Level := 2;
when '3' =>
Level := 3;
when '4' =>
Level := 4;
when '5' =>
Level := 5;
when others =>
Parse_Text (P, Token);
Parse_Text (P, C);
return;
end case;
Peek (P, C2);
if C2 /= '.' then
Parse_Text (P, Token);
Parse_Text (P, C);
Parse_Text (P, C2);
return;
end if;
-- Ignore spaces after the hN. sequence
Peek (P, C);
while C = ' ' or C = HT loop
Peek (P, C);
end loop;
Flush_Text (P);
Flush_List (P);
loop
Append (P.Text, C);
Peek (P, C);
exit when C = LF or C = CR;
end loop;
if not P.Context.Is_Hidden then
Add_Header (P.Text);
end if;
P.Empty_Line := True;
P.In_Paragraph := False;
Clear (P.Text);
end Parse_Header;
-- ------------------------------
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path!:http-link
-- ------------------------------
procedure Parse_Image (P : in out Parser;
Token : in Wiki.Strings.WChar) is
Pos : Natural := P.Line_Pos + 1;
Last : Natural;
C : Wiki.Strings.WChar;
begin
Last := Wiki.Strings.Index (P.Line, '!', Pos);
if Last = 0 then
Append (P.Text, Token);
return;
end if;
declare
Title : Wiki.Strings.UString;
Link : Wiki.Strings.UString;
Title_Pos : Natural;
Last_Pos : Natural;
begin
Title_Pos := Wiki.Strings.Index (P.Line, '(', Pos);
if Title_Pos = 0 then
Last_Pos := Last;
else
Last_Pos := Title_Pos;
end if;
while Pos < Last_Pos loop
Wiki.Strings.Append (Link, Wiki.Strings.Element (P.Line, Pos));
Pos := Pos + 1;
end loop;
if Title_Pos > 0 then
Title_Pos := Title_Pos + 1;
while Title_Pos < Last - 1 loop
Wiki.Strings.Append (Title, Wiki.Strings.Element (P.Line, Title_Pos));
Title_Pos := Title_Pos + 1;
end loop;
end if;
Flush_Text (P);
P.Line_Pos := Last;
if not P.Context.Is_Hidden then
Wiki.Attributes.Clear (P.Attributes);
Wiki.Attributes.Append (P.Attributes, "src", Link);
P.Context.Filters.Add_Image (P.Document, Wiki.Strings.To_WString (Title),
P.Attributes);
end if;
end;
end Parse_Image;
-- ------------------------------
-- Parse an external link:
-- Example:
-- "title":http-link
-- ------------------------------
procedure Parse_Link (P : in out Parser;
Token : in Wiki.Strings.WChar) is
Http : constant Wiki.Strings.WString := ":http";
Pos : Natural := P.Line_Pos + 1;
Last : Natural := Wiki.Strings.Index (P.Line, '"', Pos);
C : Wiki.Strings.WChar;
begin
if Last = 0 or Last = P.Line_Length then
Append (P.Text, Token);
return;
end if;
Pos := Last + 1;
for Expect of Http loop
C := Wiki.Strings.Element (P.Line, Pos);
if C /= Expect then
Append (P.Text, Token);
return;
end if;
Pos := Pos + 1;
end loop;
declare
Title : Wiki.Strings.UString;
Link : Wiki.Strings.UString;
begin
Pos := P.Line_Pos + 1;
while Pos < Last loop
Wiki.Strings.Append (Title, Wiki.Strings.Element (P.Line, Pos));
Pos := Pos + 1;
end loop;
Pos := Last + 2;
while Pos <= P.Line_Length loop
C := Wiki.Strings.Element (P.Line, Pos);
exit when Wiki.Helpers.Is_Space_Or_Newline (C);
Pos := Pos + 1;
Wiki.Strings.Append (Link, C);
end loop;
Flush_Text (P);
Wiki.Attributes.Clear (P.Attributes);
P.Line_Pos := Pos;
P.Empty_Line := False;
if not P.Context.Is_Hidden then
Wiki.Attributes.Append (P.Attributes, NAME_ATTR, Title);
Wiki.Attributes.Append (P.Attributes, HREF_ATTR, Link);
P.Context.Filters.Add_Link (P.Document, Wiki.Strings.To_WString (Title), P.Attributes);
end if;
end;
end Parse_Link;
-- ------------------------------
-- Parse a bold sequence or a list.
-- Example:
-- *name* (bold)
-- * item (list)
-- ------------------------------
procedure Parse_Bold_Or_List (P : in out Parser;
Token : in Wiki.Strings.WChar) is
C : Wiki.Strings.WChar;
begin
Peek (P, C);
if P.Empty_Line and C = ' ' then
Put_Back (P, C);
Common.Parse_List (P, Token);
return;
end if;
Put_Back (P, C);
Toggle_Format (P, BOLD);
end Parse_Bold_Or_List;
-- Parse a markdown table/column.
-- Example:
-- | col1 | col2 | ... | colN |
procedure Parse_Table (P : in out Parser;
Token : in Wiki.Strings.WChar) is
begin
null;
end Parse_Table;
procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser;
Token : in Wiki.Strings.WChar) is
begin
null;
end Parse_Deleted_Or_Horizontal_Rule;
end Wiki.Parsers.Textile;
|
Update the Parse_Link to parse a textile link
|
Update the Parse_Link to parse a textile link
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f41bb2593ea20b827f10db8983f00623934118b8
|
src/gen-commands.adb
|
src/gen-commands.adb
|
-----------------------------------------------------------------------
-- gen-commands -- Commands for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Gen.Configs;
with Gen.Commands.Generate;
with Gen.Commands.Project;
with Gen.Commands.Page;
with Gen.Commands.Layout;
with Gen.Commands.Model;
with Gen.Commands.Propset;
with Gen.Commands.Database;
with Gen.Commands.Info;
with Gen.Commands.Distrib;
with Gen.Commands.Plugins;
with Util.Log.Loggers;
package body Gen.Commands is
use Ada.Strings.Unbounded;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands");
Commands : Command_Maps.Map;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Cmd : in Command) is
begin
null;
end Usage;
-- ------------------------------
-- Print a message on the standard output.
-- ------------------------------
procedure Print (Cmd : in Command;
Message : in String) is
pragma Unreferenced (Cmd);
begin
Ada.Text_IO.Put_Line (Message);
end Print;
-- ------------------------------
-- Print dynamo usage
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line (Gen.Configs.RELEASE);
New_Line;
Put ("Usage: ");
Put (Ada.Command_Line.Command_Name);
Put_Line (" [-o directory] [-t templates] {command} {arguments}");
Put_Line ("where:");
Put_Line (" -o directory Directory where the Ada mapping files are generated");
Put_Line (" -t templates Directory where the Ada templates are defined");
Put_Line (" -c dir Directory where the Ada templates "
& "and configurations are defined");
end Usage;
-- ------------------------------
-- Print dynamo short usage.
-- ------------------------------
procedure Short_Help_Usage is
use Ada.Text_IO;
begin
New_Line;
Put ("Type '");
Put (Ada.Command_Line.Command_Name);
Put_Line (" help' for the list of commands.");
end Short_Help_Usage;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Help_Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Print (Position : in Command_Maps.Cursor);
use Ada.Text_IO;
use GNAT.Command_Line;
procedure Print (Position : in Command_Maps.Cursor) is
Name : constant Unbounded_String := Command_Maps.Key (Position);
begin
Put_Line (" " & To_String (Name));
end Print;
Name : constant String := Get_Argument;
begin
Log.Debug ("Execute command {0}", Name);
if Name'Length = 0 then
Usage;
New_Line;
Put ("Type '");
Put (Ada.Command_Line.Command_Name);
Put_Line (" help {command}' for help on a specific command.");
New_Line;
Put_Line ("Available subcommands:");
Commands.Iterate (Process => Print'Access);
else
declare
Target_Cmd : constant Command_Access := Find_Command (Name);
begin
if Target_Cmd = null then
Generator.Error ("Unknown command {0}", Name);
else
Target_Cmd.Help (Generator);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Help_Command;
Generator : in out Gen.Generator.Handler) is
begin
null;
end Help;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Cmd : in Command_Access;
Name : in String) is
begin
Commands.Include (Key => To_Unbounded_String (Name), New_Item => Cmd);
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- ------------------------------
function Find_Command (Name : in String) return Command_Access is
Pos : constant Command_Maps.Cursor := Commands.Find (To_Unbounded_String (Name));
begin
if Command_Maps.Has_Element (Pos) then
return Command_Maps.Element (Pos);
else
return null;
end if;
end Find_Command;
-- Generate command.
Generate_Cmd : aliased Gen.Commands.Generate.Command;
-- Create project command.
Create_Project_Cmd : aliased Gen.Commands.Project.Command;
-- Add page command.
Add_Page_Cmd : aliased Gen.Commands.Page.Command;
-- Add layout command.
Add_Layout_Cmd : aliased Gen.Commands.Layout.Command;
-- Add model command.
Add_Model_Cmd : aliased Gen.Commands.Model.Command;
-- Sets a property on the dynamo.xml project.
Propset_Cmd : aliased Gen.Commands.Propset.Command;
-- Create database command.
Database_Cmd : aliased Gen.Commands.Database.Command;
-- Project information command.
Info_Cmd : aliased Gen.Commands.Info.Command;
-- Distrib command.
Dist_Cmd : aliased Gen.Commands.Distrib.Command;
-- Create plugin command.
Create_Plugin_Cmd : aliased Gen.Commands.Plugins.Command;
-- Help command.
Help_Cmd : aliased Help_Command;
begin
Add_Command (Name => "help", Cmd => Help_Cmd'Access);
Add_Command (Name => "generate", Cmd => Generate_Cmd'Access);
Add_Command (Name => "create-project", Cmd => Create_Project_Cmd'Access);
Add_Command (Name => "add-page", Cmd => Add_Page_Cmd'Access);
Add_Command (Name => "add-layout", Cmd => Add_Layout_Cmd'Access);
Add_Command (Name => "add-model", Cmd => Add_Model_Cmd'Access);
Add_Command (Name => "propset", Cmd => Propset_Cmd'Access);
Add_Command (Name => "create-database", Cmd => Database_Cmd'Access);
Add_Command (Name => "create-plugin", Cmd => Create_Plugin_Cmd'Access);
Add_Command (Name => "dist", Cmd => Dist_Cmd'Access);
Add_Command (Name => "info", Cmd => Info_Cmd'Access);
end Gen.Commands;
|
-----------------------------------------------------------------------
-- gen-commands -- Commands for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Gen.Configs;
with Gen.Commands.Generate;
with Gen.Commands.Project;
with Gen.Commands.Page;
with Gen.Commands.Layout;
with Gen.Commands.Model;
with Gen.Commands.Propset;
with Gen.Commands.Database;
with Gen.Commands.Info;
with Gen.Commands.Distrib;
with Gen.Commands.Plugins;
with Gen.Commands.Docs;
with Util.Log.Loggers;
package body Gen.Commands is
use Ada.Strings.Unbounded;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands");
Commands : Command_Maps.Map;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Cmd : in Command) is
begin
null;
end Usage;
-- ------------------------------
-- Print a message on the standard output.
-- ------------------------------
procedure Print (Cmd : in Command;
Message : in String) is
pragma Unreferenced (Cmd);
begin
Ada.Text_IO.Put_Line (Message);
end Print;
-- ------------------------------
-- Print dynamo usage
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line (Gen.Configs.RELEASE);
New_Line;
Put ("Usage: ");
Put (Ada.Command_Line.Command_Name);
Put_Line (" [-o directory] [-t templates] {command} {arguments}");
Put_Line ("where:");
Put_Line (" -o directory Directory where the Ada mapping files are generated");
Put_Line (" -t templates Directory where the Ada templates are defined");
Put_Line (" -c dir Directory where the Ada templates "
& "and configurations are defined");
end Usage;
-- ------------------------------
-- Print dynamo short usage.
-- ------------------------------
procedure Short_Help_Usage is
use Ada.Text_IO;
begin
New_Line;
Put ("Type '");
Put (Ada.Command_Line.Command_Name);
Put_Line (" help' for the list of commands.");
end Short_Help_Usage;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Help_Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Print (Position : in Command_Maps.Cursor);
use Ada.Text_IO;
use GNAT.Command_Line;
procedure Print (Position : in Command_Maps.Cursor) is
Name : constant Unbounded_String := Command_Maps.Key (Position);
begin
Put_Line (" " & To_String (Name));
end Print;
Name : constant String := Get_Argument;
begin
Log.Debug ("Execute command {0}", Name);
if Name'Length = 0 then
Usage;
New_Line;
Put ("Type '");
Put (Ada.Command_Line.Command_Name);
Put_Line (" help {command}' for help on a specific command.");
New_Line;
Put_Line ("Available subcommands:");
Commands.Iterate (Process => Print'Access);
else
declare
Target_Cmd : constant Command_Access := Find_Command (Name);
begin
if Target_Cmd = null then
Generator.Error ("Unknown command {0}", Name);
else
Target_Cmd.Help (Generator);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Help_Command;
Generator : in out Gen.Generator.Handler) is
begin
null;
end Help;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Cmd : in Command_Access;
Name : in String) is
begin
Commands.Include (Key => To_Unbounded_String (Name), New_Item => Cmd);
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- ------------------------------
function Find_Command (Name : in String) return Command_Access is
Pos : constant Command_Maps.Cursor := Commands.Find (To_Unbounded_String (Name));
begin
if Command_Maps.Has_Element (Pos) then
return Command_Maps.Element (Pos);
else
return null;
end if;
end Find_Command;
-- Generate command.
Generate_Cmd : aliased Gen.Commands.Generate.Command;
-- Create project command.
Create_Project_Cmd : aliased Gen.Commands.Project.Command;
-- Add page command.
Add_Page_Cmd : aliased Gen.Commands.Page.Command;
-- Add layout command.
Add_Layout_Cmd : aliased Gen.Commands.Layout.Command;
-- Add model command.
Add_Model_Cmd : aliased Gen.Commands.Model.Command;
-- Sets a property on the dynamo.xml project.
Propset_Cmd : aliased Gen.Commands.Propset.Command;
-- Create database command.
Database_Cmd : aliased Gen.Commands.Database.Command;
-- Project information command.
Info_Cmd : aliased Gen.Commands.Info.Command;
-- Distrib command.
Dist_Cmd : aliased Gen.Commands.Distrib.Command;
-- Create plugin command.
Create_Plugin_Cmd : aliased Gen.Commands.Plugins.Command;
-- Documentation command.
Doc_Plugin_Cmd : aliased Gen.Commands.Docs.Command;
-- Help command.
Help_Cmd : aliased Help_Command;
begin
Add_Command (Name => "help", Cmd => Help_Cmd'Access);
Add_Command (Name => "generate", Cmd => Generate_Cmd'Access);
Add_Command (Name => "create-project", Cmd => Create_Project_Cmd'Access);
Add_Command (Name => "add-page", Cmd => Add_Page_Cmd'Access);
Add_Command (Name => "add-layout", Cmd => Add_Layout_Cmd'Access);
Add_Command (Name => "add-model", Cmd => Add_Model_Cmd'Access);
Add_Command (Name => "propset", Cmd => Propset_Cmd'Access);
Add_Command (Name => "create-database", Cmd => Database_Cmd'Access);
Add_Command (Name => "create-plugin", Cmd => Create_Plugin_Cmd'Access);
Add_Command (Name => "dist", Cmd => Dist_Cmd'Access);
Add_Command (Name => "info", Cmd => Info_Cmd'Access);
Add_Command (Name => "build-doc", Cmd => Doc_Plugin_Cmd'Access);
end Gen.Commands;
|
Add the build-doc command
|
Add the build-doc command
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
468e3dd8e3081e1f20ca41b6ccdb20be7deebabb
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.MIME;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- Get a printable representation of the email recipients.
function Image (Recipients : in AWS.SMTP.Recipients) return String;
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
pragma Unreferenced (Kind);
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String) is
begin
if Length (Alternative) = 0 then
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (Content));
else
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (Content,
Content_Type => Content_Type));
end if;
end Set_Body;
-- ------------------------------
-- Add an attachment with the given content.
-- ------------------------------
overriding
procedure Add_Attachment (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is
Data : constant AWS.Attachments.Content
:= AWS.Attachments.Value (Data => Content,
Content_Id => Content_Id,
Content_Type => Content_Type);
begin
AWS.Attachments.Add (Attachments => Message.Attachments,
Name => Content_Id,
Data => Data);
end Add_Attachment;
-- ------------------------------
-- Get a printable representation of the email recipients.
-- ------------------------------
function Image (Recipients : in AWS.SMTP.Recipients) return String is
Result : Unbounded_String;
begin
for I in Recipients'Range loop
Append (Result, AWS.SMTP.Image (Recipients (I)));
end loop;
return To_String (Result);
end Image;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Attachments => Message.Attachments,
Status => Result);
if not AWS.SMTP.Is_Ok (Result) then
Log.Error ("Cannot send email: {0}",
AWS.SMTP.Status_Message (Result));
end if;
else
Log.Info ("Disable send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class) is separate;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Port := Positive'Value (Port);
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Self := Result;
Initialize (Result.all, Props);
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- Get a printable representation of the email recipients.
function Image (Recipients : in AWS.SMTP.Recipients) return String;
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
pragma Unreferenced (Kind);
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String) is
begin
if Length (Alternative) = 0 then
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (To_String (Content)));
else
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (To_String (Content),
Content_Type => Content_Type));
end if;
end Set_Body;
-- ------------------------------
-- Add an attachment with the given content.
-- ------------------------------
overriding
procedure Add_Attachment (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is
Data : constant AWS.Attachments.Content
:= AWS.Attachments.Value (Data => To_String (Content),
Content_Id => Content_Id,
Content_Type => Content_Type);
begin
AWS.Attachments.Add (Attachments => Message.Attachments,
Name => Content_Id,
Data => Data);
end Add_Attachment;
-- ------------------------------
-- Get a printable representation of the email recipients.
-- ------------------------------
function Image (Recipients : in AWS.SMTP.Recipients) return String is
Result : Unbounded_String;
begin
for I in Recipients'Range loop
Append (Result, AWS.SMTP.Image (Recipients (I)));
end loop;
return To_String (Result);
end Image;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Attachments => Message.Attachments,
Status => Result);
if not AWS.SMTP.Is_Ok (Result) then
Log.Error ("Cannot send email: {0}",
AWS.SMTP.Status_Message (Result));
end if;
else
Log.Info ("Disable send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class) is separate;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Port := Positive'Value (Port);
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Self := Result;
Initialize (Result.all, Props);
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
Fix compilation to build with old AWS version
|
Fix compilation to build with old AWS version
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9bf3b1255f594de153e30fef77ddd64111eb0e6f
|
src/wiki-buffers.adb
|
src/wiki-buffers.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 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.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Wiki.Helpers;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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 Wiki.Strings.WChar) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- 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) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : constant Positive := Pos;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : constant Positive := From;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
-- ------------------------------
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
-- ------------------------------
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural) is
Block : Wiki.Buffers.Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
Main_Loop :
while Block /= null loop
declare
Last : constant Natural := Block.Last;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Block.Content (Pos)) loop
Pos := Pos + 1;
Count := Count + 1;
end loop;
exit Main_Loop when Pos <= Last;
end;
Block := Block.Next_Block;
Pos := 1;
end loop Main_Loop;
Buffer := Block;
From := Pos;
end Skip_Spaces;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 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.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Wiki.Helpers;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
exit when Content = null;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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 Wiki.Strings.WChar) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- 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) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : constant Positive := Pos;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : constant Positive := From;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
-- ------------------------------
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
-- ------------------------------
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural) is
Block : Wiki.Buffers.Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
Main_Loop :
while Block /= null loop
declare
Last : constant Natural := Block.Last;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Block.Content (Pos)) loop
Pos := Pos + 1;
Count := Count + 1;
end loop;
exit Main_Loop when Pos <= Last;
end;
Block := Block.Next_Block;
Pos := 1;
end loop Main_Loop;
Buffer := Block;
From := Pos;
end Skip_Spaces;
-- ------------------------------
-- Skip one optional space or tab.
-- ------------------------------
procedure Skip_Optional_Space (Buffer : in out Buffer_Access;
From : in out Positive) is
begin
if From <= Buffer.Last
and then Wiki.Helpers.Is_Space (Buffer.Content (From))
then
Next (Buffer, From);
end if;
end Skip_Optional_Space;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
Implement the Skip_Optional_Space procedure
|
Implement the Skip_Optional_Space procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6728ca8903a0f30e85e1b95b4633d02d07683874
|
src/wiki-strings.ads
|
src/wiki-strings.ads
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Characters.Conversions;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Substitute : in Character := ' ') return String
renames Ada.Characters.Conversions.To_String;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
function To_WString (S : in String) return WString
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Null_UString : UString
renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String;
package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar,
Input => WString,
Chunk_Size => 512);
subtype BString is Wide_Wide_Builders.Builder;
end Wiki.Strings;
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Characters.Conversions;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Substitute : in Character := ' ') return String
renames Ada.Characters.Conversions.To_String;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
function To_WString (S : in String) return WString
renames Ada.Characters.Conversions.To_Wide_Wide_String;
procedure Append (Into : in out UString; S : in WString)
renames Ada.Strings.Wide_Wide_Unbounded.Append;
Null_UString : UString
renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String;
package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar,
Input => WString,
Chunk_Size => 512);
subtype BString is Wide_Wide_Builders.Builder;
end Wiki.Strings;
|
Declare the Append procedure
|
Declare the Append procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a1e3e8f918482426a79ae114174ef46f1840db5e
|
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_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_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_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_TIME,
F_EVENT,
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;
|
Add F_START_TIME, F_END_TIME, F_EVENT_RANGE, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT
|
Add F_START_TIME, F_END_TIME, F_EVENT_RANGE, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
071a16f5313cd2c7069d50ee597442e640b79f01
|
src/orka/implementation/orka-rendering-framebuffers.adb
|
src/orka/implementation/orka-rendering-framebuffers.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Strings.Fixed;
with GL.Pixels;
with GL.Viewports;
with Orka.Containers.Bounded_Vectors;
package body Orka.Rendering.Framebuffers is
package Attachment_Vectors is new Containers.Bounded_Vectors (Positive, FB.Attachment_Point);
package Default_Attachment_Vectors is new Containers.Bounded_Vectors
(Positive, FB.Default_Attachment_Point);
function Create_Framebuffer
(Width, Height, Samples : Size) return Framebuffer is
begin
return Result : Framebuffer
(Default => False,
Width => Width,
Height => Height,
Samples => Samples)
do
Result.GL_Framebuffer.Set_Default_Width (Width);
Result.GL_Framebuffer.Set_Default_Height (Height);
Result.GL_Framebuffer.Set_Default_Samples (Samples);
Result.Set_Draw_Buffers ((0 => GL.Buffers.Color_Attachment0));
end return;
end Create_Framebuffer;
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context'Class) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => Samples));
function Create_Framebuffer
(Width, Height : Size) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => 0));
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
is (Create_Default_Framebuffer (Size (Window.Width), Size (Window.Height)));
-- TODO Or store a Window_Ptr so we can adjust viewport when window gets resized?
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer is
begin
return Result : Framebuffer :=
(Default => True,
Width => Width,
Height => Height,
Samples => 0,
GL_Framebuffer => GL.Objects.Framebuffers.Default_Framebuffer,
others => <>)
do
-- Assumes a double-buffered context (Front_Left for single-buffered)
Result.Set_Draw_Buffers ((0 => GL.Buffers.Back_Left));
end return;
end Create_Default_Framebuffer;
-----------------------------------------------------------------------------
function GL_Framebuffer (Object : Framebuffer) return GL.Objects.Framebuffers.Framebuffer
is (Object.GL_Framebuffer);
-----------------------------------------------------------------------------
function Image (Object : Framebuffer) return String is
function Trim (Value : String) return String is
(Ada.Strings.Fixed.Trim (Value, Ada.Strings.Both));
Width : constant String := Trim (Object.Width'Image);
Height : constant String := Trim (Object.Height'Image);
Default : constant String := (if Object.Default then " default" else "");
begin
return Width & " x " & Height & Default & " framebuffer";
end Image;
procedure Use_Framebuffer (Object : Framebuffer) is
use GL.Objects.Framebuffers;
begin
GL.Objects.Framebuffers.Draw_Target.Bind (Object.GL_Framebuffer);
-- Adjust viewport
GL.Viewports.Set_Viewports
((0 => (X => 0.0,
Y => 0.0,
Width => Single (Object.Width),
Height => Single (Object.Height))
));
-- Check attachments
if not Object.Default then
declare
Status : constant Framebuffer_Status := Object.GL_Framebuffer.Status (Draw_Target);
begin
if Status /= Complete then
raise Framebuffer_Incomplete_Error with Status'Image;
end if;
end;
end if;
end Use_Framebuffer;
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values) is
begin
Object.Defaults := Values;
end Set_Default_Values;
function Default_Values (Object : Framebuffer) return Buffer_Values is (Object.Defaults);
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector) is
begin
Object.GL_Framebuffer.Set_Read_Buffer (Buffer);
end Set_Read_Buffer;
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List) is
begin
Object.GL_Framebuffer.Set_Draw_Buffers (Buffers);
Object.Draw_Buffers.Replace_Element (Buffers);
end Set_Draw_Buffers;
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True))
is
Depth_Stencil : constant Boolean
:= Object.Default or else Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
-- This procedure is used because it may be faster for
-- combined depth/stencil textures
Object.GL_Framebuffer.Clear_Depth_And_Stencil_Buffer
(Depth_Value => Object.Defaults.Depth,
Stencil_Value => Object.Defaults.Stencil);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Object.GL_Framebuffer.Clear_Depth_Buffer (Object.Defaults.Depth);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Object.GL_Framebuffer.Clear_Stencil_Buffer (Object.Defaults.Stencil);
end if;
end if;
end if;
if Mask.Color then
declare
procedure Clear_Attachments (List : GL.Buffers.Color_Buffer_List) is
use all type GL.Buffers.Color_Buffer_Selector;
Index : GL.Buffers.Draw_Buffer_Index := GL.Buffers.Draw_Buffer_Index'First;
begin
for Buffer of List loop
if Buffer /= None then
if Object.Default then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, GL.Pixels.Float_Type, Object.Defaults.Color);
else
declare
Point : constant FB.Attachment_Point := Color_Attachment_Point'Val
(GL.Buffers.Color_Buffer_Selector'Pos (Buffer)
- GL.Buffers.Color_Buffer_Selector'Pos (GL.Buffers.Color_Attachment0)
+ Color_Attachment_Point'Pos (Color_Attachment_Point'First));
begin
if Object.Has_Attachment (Point) then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, Object.Attachments (Point).Element.Red_Type,
Object.Defaults.Color);
end if;
end;
end if;
end if;
Index := Index + 1;
end loop;
end Clear_Attachments;
begin
Object.Draw_Buffers.Query_Element (Clear_Attachments'Access);
end;
end if;
end Clear;
procedure Invalidate_Non_Default
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Attachment_Vectors.Vector (Capacity => Attachment_Array'Length);
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
procedure Invalidate_Attachments (Elements : Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
Attachments.Append (FB.Depth_Stencil_Attachment);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Attachments.Append (FB.Depth_Attachment);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Attachments.Append (FB.Stencil_Attachment);
end if;
end if;
end if;
if Mask.Color then
for Attachment in Color_Attachment_Point loop
if Object.Has_Attachment (Attachment) then
Attachments.Append (Attachment);
end if;
end loop;
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate_Non_Default;
procedure Invalidate_Default
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Default_Attachment_Vectors.Vector (Capacity => 3);
procedure Invalidate_Attachments (Elements : Default_Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Default_Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth then
Attachments.Append (FB.Depth);
end if;
if Mask.Stencil then
Attachments.Append (FB.Stencil);
end if;
if Mask.Color then
-- Assumes a double-buffered context (Front_Left for single-buffered)
Attachments.Append (FB.Back_Left);
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate_Default;
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits) is
begin
if Object.Default then
Object.Invalidate_Default (Mask);
else
Object.Invalidate_Non_Default (Mask);
end if;
end Invalidate;
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) is
begin
FB.Blit
(Object.GL_Framebuffer, Subject.GL_Framebuffer,
0, 0, Object.Width, Object.Height,
0, 0, Subject.Width, Subject.Height,
Mask, GL.Objects.Textures.Nearest);
end Resolve_To;
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0) is
begin
Object.GL_Framebuffer.Attach_Texture (Attachment, Texture, Level);
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach;
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0)
is
use all type GL.Pixels.Internal_Format;
begin
case Texture.Internal_Format is
when Depth24_Stencil8 | Depth32F_Stencil8 =>
Object.Attach (FB.Depth_Stencil_Attachment, Texture, Level);
when Depth_Component16 | Depth_Component24 | Depth_Component32F =>
Object.Attach (FB.Depth_Attachment, Texture, Level);
when Stencil_Index8 =>
Object.Attach (FB.Stencil_Attachment, Texture, Level);
when others =>
Object.Attach (FB.Color_Attachment_0, Texture, Level);
end case;
end Attach;
procedure Attach_Layer
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Layer : Natural;
Level : Textures.Mipmap_Level := 0) is
begin
Object.GL_Framebuffer.Attach_Texture_Layer (Attachment, Texture, Level, Layer => Layer);
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach_Layer;
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point) is
begin
Object.GL_Framebuffer.Detach (Attachment);
Object.Attachments (Attachment).Clear;
end Detach;
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean
is (not Object.Attachments (Attachment).Is_Empty);
end Orka.Rendering.Framebuffers;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Strings.Fixed;
with GL.Pixels;
with GL.Viewports;
with Orka.Containers.Bounded_Vectors;
package body Orka.Rendering.Framebuffers is
package Attachment_Vectors is new Containers.Bounded_Vectors (Positive, FB.Attachment_Point);
package Default_Attachment_Vectors is new Containers.Bounded_Vectors
(Positive, FB.Default_Attachment_Point);
function Create_Framebuffer
(Width, Height, Samples : Size) return Framebuffer is
begin
return Result : Framebuffer
(Default => False,
Width => Width,
Height => Height,
Samples => Samples)
do
Result.GL_Framebuffer.Set_Default_Width (Width);
Result.GL_Framebuffer.Set_Default_Height (Height);
Result.GL_Framebuffer.Set_Default_Samples (Samples);
Result.Set_Draw_Buffers ((0 => GL.Buffers.Color_Attachment0));
end return;
end Create_Framebuffer;
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context'Class) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => Samples));
function Create_Framebuffer
(Width, Height : Size) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => 0));
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
is (Create_Default_Framebuffer (Size (Window.Width), Size (Window.Height)));
-- TODO Or store a Window_Ptr so we can adjust viewport when window gets resized?
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer is
begin
return Result : Framebuffer :=
(Default => True,
Width => Width,
Height => Height,
Samples => 0,
GL_Framebuffer => GL.Objects.Framebuffers.Default_Framebuffer,
others => <>)
do
-- Assumes a double-buffered context (Front_Left for single-buffered)
Result.Set_Draw_Buffers ((0 => GL.Buffers.Back_Left));
end return;
end Create_Default_Framebuffer;
-----------------------------------------------------------------------------
function GL_Framebuffer (Object : Framebuffer) return GL.Objects.Framebuffers.Framebuffer
is (Object.GL_Framebuffer);
-----------------------------------------------------------------------------
function Image (Object : Framebuffer) return String is
function Trim (Value : String) return String is
(Ada.Strings.Fixed.Trim (Value, Ada.Strings.Both));
Width : constant String := Trim (Object.Width'Image);
Height : constant String := Trim (Object.Height'Image);
Default : constant String := (if Object.Default then " default" else "");
begin
return Width & " x " & Height & Default & " framebuffer";
end Image;
procedure Use_Framebuffer (Object : Framebuffer) is
use GL.Objects.Framebuffers;
begin
GL.Objects.Framebuffers.Draw_Target.Bind (Object.GL_Framebuffer);
-- Adjust viewport
GL.Viewports.Set_Viewports
((0 => (X => 0.0,
Y => 0.0,
Width => Single (Object.Width),
Height => Single (Object.Height))
));
-- Check attachments
if not Object.Default then
declare
Status : constant Framebuffer_Status := Object.GL_Framebuffer.Status (Draw_Target);
begin
if Status /= Complete then
raise Framebuffer_Incomplete_Error with Status'Image;
end if;
end;
end if;
end Use_Framebuffer;
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values) is
begin
Object.Defaults := Values;
end Set_Default_Values;
function Default_Values (Object : Framebuffer) return Buffer_Values is (Object.Defaults);
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector) is
begin
Object.GL_Framebuffer.Set_Read_Buffer (Buffer);
end Set_Read_Buffer;
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List) is
begin
Object.GL_Framebuffer.Set_Draw_Buffers (Buffers);
Object.Draw_Buffers.Replace_Element (Buffers);
end Set_Draw_Buffers;
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True))
is
Depth_Stencil : constant Boolean
:= Object.Default or else Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
-- This procedure is used because it may be faster for
-- combined depth/stencil textures
Object.GL_Framebuffer.Clear_Depth_And_Stencil_Buffer
(Depth_Value => Object.Defaults.Depth,
Stencil_Value => Object.Defaults.Stencil);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Object.GL_Framebuffer.Clear_Depth_Buffer (Object.Defaults.Depth);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Object.GL_Framebuffer.Clear_Stencil_Buffer (Object.Defaults.Stencil);
end if;
end if;
end if;
if Mask.Color then
declare
procedure Clear_Attachments (List : GL.Buffers.Color_Buffer_List) is
use all type GL.Buffers.Color_Buffer_Selector;
Index : GL.Buffers.Draw_Buffer_Index := GL.Buffers.Draw_Buffer_Index'First;
begin
for Buffer of List loop
if Buffer /= None then
if Object.Default then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, GL.Pixels.Float_Type, Object.Defaults.Color);
else
declare
Point : constant FB.Attachment_Point := Color_Attachment_Point'Val
(GL.Buffers.Color_Buffer_Selector'Pos (Buffer)
- GL.Buffers.Color_Buffer_Selector'Pos (GL.Buffers.Color_Attachment0)
+ Color_Attachment_Point'Pos (Color_Attachment_Point'First));
begin
if Object.Has_Attachment (Point) then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, Object.Attachments (Point).Element.Red_Type,
Object.Defaults.Color);
end if;
end;
end if;
end if;
Index := Index + 1;
end loop;
end Clear_Attachments;
begin
Object.Draw_Buffers.Query_Element (Clear_Attachments'Access);
end;
end if;
end Clear;
procedure Invalidate_Non_Default
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Attachment_Vectors.Vector (Capacity => Attachment_Array'Length);
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
procedure Invalidate_Attachments (Elements : Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
Attachments.Append (FB.Depth_Stencil_Attachment);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Attachments.Append (FB.Depth_Attachment);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Attachments.Append (FB.Stencil_Attachment);
end if;
end if;
end if;
if Mask.Color then
for Attachment in Color_Attachment_Point loop
if Object.Has_Attachment (Attachment) then
Attachments.Append (Attachment);
end if;
end loop;
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate_Non_Default;
procedure Invalidate_Default
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Default_Attachment_Vectors.Vector (Capacity => 3);
procedure Invalidate_Attachments (Elements : Default_Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Default_Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth then
Attachments.Append (FB.Depth);
end if;
if Mask.Stencil then
Attachments.Append (FB.Stencil);
end if;
if Mask.Color then
-- Assumes a double-buffered context (Front_Left for single-buffered)
Attachments.Append (FB.Back_Left);
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate_Default;
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits) is
begin
if Object.Default then
Object.Invalidate_Default (Mask);
else
Object.Invalidate_Non_Default (Mask);
end if;
end Invalidate;
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False))
is
use all type GL.Objects.Textures.Minifying_Function;
begin
FB.Blit
(Object.GL_Framebuffer, Subject.GL_Framebuffer,
0, 0, Object.Width, Object.Height,
0, 0, Subject.Width, Subject.Height,
Mask, (if Mask.Depth or Mask.Stencil then Nearest else Linear));
end Resolve_To;
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0) is
begin
Object.GL_Framebuffer.Attach_Texture (Attachment, Texture, Level);
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach;
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0)
is
use all type GL.Pixels.Internal_Format;
begin
case Texture.Internal_Format is
when Depth24_Stencil8 | Depth32F_Stencil8 =>
Object.Attach (FB.Depth_Stencil_Attachment, Texture, Level);
when Depth_Component16 | Depth_Component24 | Depth_Component32F =>
Object.Attach (FB.Depth_Attachment, Texture, Level);
when Stencil_Index8 =>
Object.Attach (FB.Stencil_Attachment, Texture, Level);
when others =>
Object.Attach (FB.Color_Attachment_0, Texture, Level);
end case;
end Attach;
procedure Attach_Layer
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Layer : Natural;
Level : Textures.Mipmap_Level := 0) is
begin
Object.GL_Framebuffer.Attach_Texture_Layer (Attachment, Texture, Level, Layer => Layer);
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach_Layer;
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point) is
begin
Object.GL_Framebuffer.Detach (Attachment);
Object.Attachments (Attachment).Clear;
end Detach;
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean
is (not Object.Attachments (Attachment).Is_Empty);
end Orka.Rendering.Framebuffers;
|
Use linear interpolation when blitting framebuffer's color buffer
|
orka: Use linear interpolation when blitting framebuffer's color buffer
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
2c6f589efc98af451e4f610dc07703f478d14ec8
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Set_Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return "role";
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description.
-- ------------------------------
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Set_Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
Implement Get_Name
|
Implement Get_Name
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
827c3ce72ca31f16885f809a4c436d3beed1ff3e
|
awa/plugins/awa-counters/src/awa-counters-definition.ads
|
awa/plugins/awa-counters/src/awa-counters-definition.ads
|
-----------------------------------------------------------------------
-- awa-counters-definition -- Counter definition
-- 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.
-----------------------------------------------------------------------
-- The <tt>AWA.Counters.Definition</tt> package is instantiated for each counter definition.
generic
Table : ADO.Schemas.Class_Mapping_Access;
Field : String;
package AWA.Counters.Definition is
Def_Name : aliased constant String := Field;
-- Get the counter definition index.
function Index return Counter_Index_Type;
private
package Def is new Counter_Arrays.Definition (Counter_Def '(Table, Def_Name'Access));
-- Get the counter definition index.
function Index return Counter_Index_Type renames Def.Kind;
end AWA.Counters.Definition;
|
-----------------------------------------------------------------------
-- awa-counters-definition -- Counter definition
-- 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.
-----------------------------------------------------------------------
-- The <tt>AWA.Counters.Definition</tt> package is instantiated for each counter definition.
generic
Table : ADO.Schemas.Class_Mapping_Access;
Field : String := "";
package AWA.Counters.Definition is
Def_Name : aliased constant String := Field;
-- Get the counter definition index.
function Index return Counter_Index_Type;
private
package Def is new Counter_Arrays.Definition (Counter_Def '(Table, Def_Name'Access));
-- Get the counter definition index.
function Index return Counter_Index_Type renames Def.Kind;
end AWA.Counters.Definition;
|
Change the Field parameter to be optional
|
Change the Field parameter to be optional
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f6f2e203c5a0eb73e4e4af57d3f75ea735fdc5a1
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
Stream.Write ('"');
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
Stream.Write ('"');
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
Stream.Write ("""null""");
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("""true""");
else
Stream.Write ("""false""");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (",");
end if;
Stream.Column := Stream.Column + 1;
Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (",");
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Parser'Class (Handler).Finish_Object ("");
end if;
Parser'Class (Handler).Start_Object ("");
end if;
Handler.Row := Row;
Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
Context : Element_Context_Access;
begin
Context_Stack.Push (Handler.Stack);
Context := Context_Stack.Current (Handler.Stack);
Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access;
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Context_Stack.Pop (Handler.Stack);
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Parser'Class (Handler).Finish_Object ("");
end if;
Parser'Class (Handler).Start_Object ("");
end if;
Handler.Row := Row;
Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
Context : Element_Context_Access;
begin
Context_Stack.Push (Handler.Stack);
Context := Context_Stack.Current (Handler.Stack);
Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access;
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Context_Stack.Pop (Handler.Stack);
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
Implement Set_Field_Separator and Set_Quotes Update the CSV output stream to quote or not the strings and use the separator that was configured
|
Implement Set_Field_Separator and Set_Quotes
Update the CSV output stream to quote or not the strings and use the separator that was configured
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
db13d420c875093dfbf01ce8b6f375ce8ac38afb
|
samples/beans/facebook.adb
|
samples/beans/facebook.adb
|
-----------------------------------------------------------------------
-- facebook - Use Facebook Graph API
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Clients;
with Util.Http.Rest;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with ASF.Sessions;
with ASF.Contexts.Faces;
with ASF.Events.Faces.Actions;
package body Facebook is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook");
type Friend_Field_Type is (FIELD_NAME, FIELD_ID);
type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE,
FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
end case;
end Set_Member;
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field),
Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
when FIELD_FROM =>
Into.From := Value;
when FIELD_MESSAGE =>
Into.Message := Value;
when FIELD_LINK =>
Into.Link := Value;
when FIELD_PICTURE =>
Into.Picture := Value;
when FIELD_ICON =>
Into.Icon := Value;
when FIELD_DESCRIPTION =>
Into.Description := Value;
end case;
end Set_Member;
package Friend_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info,
Element_Type_Access => Friend_Info_Access,
Fields => Friend_Field_Type,
Set_Member => Set_Member);
package Friend_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors,
Element_Mapper => Friend_Mapper);
package Feed_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info,
Element_Type_Access => Feed_Info_Access,
Fields => Feed_Field_Type,
Set_Member => Set_Member);
package Feed_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors,
Element_Mapper => Feed_Mapper);
Friend_Map : aliased Friend_Mapper.Mapper;
Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper;
Feed_Map : aliased Feed_Mapper.Mapper;
Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper;
procedure Get_Friends is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper);
procedure Get_Feeds is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper);
-- ------------------------------
-- Get the access token from the user session.
-- ------------------------------
function Get_Access_Token return String is
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return "";
end if;
declare
S : ASF.Sessions.Session := Context.Get_Session;
begin
if not S.Is_Valid then
return "";
end if;
declare
Token : Util.Beans.Objects.Object := S.Get_Attribute ("access_token");
begin
if Util.Beans.Objects.Is_Null (Token) then
return "";
else
return Util.Beans.Objects.To_String (Token);
end if;
end;
end;
end Get_Access_Token;
-- ------------------------------
-- 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 Friend_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return From.Name;
elsif Name = "id" then
return From.Id;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Feed_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return From.Id;
elsif Name = "name" then
return From.Name;
elsif Name = "from" then
return From.From;
elsif Name = "message" then
return From.Message;
elsif Name = "picture" then
return From.Picture;
elsif Name = "link" then
return From.Link;
elsif Name = "description" then
return From.Description;
elsif Name = "icon" then
return From.Icon;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "hasAccessToken" then
return Util.Beans.Objects.To_Object (False);
end if;
return Friend_List.List_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create a Friend_List bean instance.
-- ------------------------------
function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Friend_List_Bean_Access := new Friend_List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
declare
C : Util.Http.Rest.Client;
begin
Log.Info ("Getting the Facebook friends");
Get_Friends ("https://graph.facebook.com/me/friends?access_token="
& Token,
Friend_Vector_Map'Access,
"/data",
List.List'Access);
end;
end if;
return List.all'Access;
end Create_Friends_Bean;
-- ------------------------------
-- Build and return a Facebook feed list.
-- ------------------------------
function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Feed_List.List_Bean_Access := new Feed_List.List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
declare
C : Util.Http.Rest.Client;
begin
Log.Info ("Getting the Facebook feeds");
Get_Feeds ("https://graph.facebook.com/me/home?access_token="
& Token,
Feed_Vector_Map'Access,
"/data",
List.List'Access);
end;
end if;
return List.all'Access;
end Create_Feed_List_Bean;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
overriding
function Get_Value (From : in Facebook_Auth;
Name : in String) return Util.Beans.Objects.Object is
use type ASF.Contexts.Faces.Faces_Context_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if F /= null and Name = "authenticate_url" then
declare
S : ASF.Sessions.Session := F.Get_Session (True);
Id : constant String := S.Get_Id;
State : constant String := From.Get_State (Id);
Params : constant String := From.Get_Auth_Params (State, "read_stream");
begin
Log.Info ("OAuth params: {0}", Params);
return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?"
& Params);
end;
elsif F /= null and Name = "isAuthenticated" then
declare
S : ASF.Sessions.Session := F.Get_Session (False);
begin
if S.Is_Valid and
then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.To_Object (False);
end if;
end;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Authenticate result from Facebook.
-- ------------------------------
procedure Authenticate (From : in out Facebook_Auth;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
use type Security.OAuth.Clients.Access_Token_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := F.Get_Session;
State : constant String := F.Get_Parameter (Security.OAuth.State);
Code : constant String := F.Get_Parameter (Security.OAuth.Code);
begin
Log.Info ("Auth code {0} for state {1}", Code, State);
if Session.Is_Valid then
if From.Is_Valid_State (Session.Get_Id, State) then
declare
Acc : Security.OAuth.Clients.Access_Token_Access
:= From.Request_Access_Token (Code);
begin
if Acc /= null then
Log.Info ("Access token is {0}", Acc.Get_Name);
Session.Set_Attribute ("access_token",
Util.Beans.Objects.To_Object (Acc.Get_Name));
end if;
end;
end if;
end if;
end Authenticate;
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth,
Method => Authenticate,
Name => "authenticate");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Authenticate_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Facebook_Auth)
return Util.Beans.Methods.Method_Binding_Array_Access is
begin
return Binding_Array'Access;
end Get_Method_Bindings;
begin
Friend_Map.Add_Default_Mapping;
Friend_Vector_Map.Set_Mapping (Friend_Map'Access);
Feed_Map.Add_Mapping ("id", FIELD_ID);
Feed_Map.Add_Mapping ("name", FIELD_NAME);
Feed_Map.Add_Mapping ("message", FIELD_MESSAGE);
Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION);
Feed_Map.Add_Mapping ("from/name", FIELD_FROM);
Feed_Map.Add_Mapping ("picture", FIELD_PICTURE);
Feed_Map.Add_Mapping ("link", FIELD_LINK);
Feed_Map.Add_Mapping ("icon", FIELD_ICON);
Feed_Vector_Map.Set_Mapping (Feed_Map'Access);
end Facebook;
|
-----------------------------------------------------------------------
-- facebook - Use Facebook Graph API
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Rest;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with ASF.Sessions;
with ASF.Contexts.Faces;
with ASF.Events.Faces.Actions;
package body Facebook is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook");
type Friend_Field_Type is (FIELD_NAME, FIELD_ID);
type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE,
FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
end case;
end Set_Member;
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field),
Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
when FIELD_FROM =>
Into.From := Value;
when FIELD_MESSAGE =>
Into.Message := Value;
when FIELD_LINK =>
Into.Link := Value;
when FIELD_PICTURE =>
Into.Picture := Value;
when FIELD_ICON =>
Into.Icon := Value;
when FIELD_DESCRIPTION =>
Into.Description := Value;
end case;
end Set_Member;
package Friend_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info,
Element_Type_Access => Friend_Info_Access,
Fields => Friend_Field_Type,
Set_Member => Set_Member);
package Friend_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors,
Element_Mapper => Friend_Mapper);
package Feed_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info,
Element_Type_Access => Feed_Info_Access,
Fields => Feed_Field_Type,
Set_Member => Set_Member);
package Feed_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors,
Element_Mapper => Feed_Mapper);
Friend_Map : aliased Friend_Mapper.Mapper;
Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper;
Feed_Map : aliased Feed_Mapper.Mapper;
Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper;
procedure Get_Friends is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper);
procedure Get_Feeds is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper);
-- ------------------------------
-- Get the access token from the user session.
-- ------------------------------
function Get_Access_Token return String is
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return "";
end if;
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
begin
if not S.Is_Valid then
return "";
end if;
declare
Token : constant Util.Beans.Objects.Object := S.Get_Attribute ("access_token");
begin
if Util.Beans.Objects.Is_Null (Token) then
return "";
else
return Util.Beans.Objects.To_String (Token);
end if;
end;
end;
end Get_Access_Token;
-- ------------------------------
-- 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 Friend_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return From.Name;
elsif Name = "id" then
return From.Id;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Feed_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return From.Id;
elsif Name = "name" then
return From.Name;
elsif Name = "from" then
return From.From;
elsif Name = "message" then
return From.Message;
elsif Name = "picture" then
return From.Picture;
elsif Name = "link" then
return From.Link;
elsif Name = "description" then
return From.Description;
elsif Name = "icon" then
return From.Icon;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "hasAccessToken" then
return Util.Beans.Objects.To_Object (False);
end if;
return Friend_List.List_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create a Friend_List bean instance.
-- ------------------------------
function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Friend_List_Bean_Access := new Friend_List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook friends");
Get_Friends ("https://graph.facebook.com/me/friends?access_token="
& Token,
Friend_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Friends_Bean;
-- ------------------------------
-- Build and return a Facebook feed list.
-- ------------------------------
function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Feed_List.List_Bean_Access := new Feed_List.List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook feeds");
Get_Feeds ("https://graph.facebook.com/me/home?access_token="
& Token,
Feed_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Feed_List_Bean;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
overriding
function Get_Value (From : in Facebook_Auth;
Name : in String) return Util.Beans.Objects.Object is
use type ASF.Contexts.Faces.Faces_Context_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if F /= null and Name = "authenticate_url" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (True);
Id : constant String := S.Get_Id;
State : constant String := From.Get_State (Id);
Params : constant String := From.Get_Auth_Params (State, "read_stream");
begin
Log.Info ("OAuth params: {0}", Params);
return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?"
& Params);
end;
elsif F /= null and Name = "isAuthenticated" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (False);
begin
if S.Is_Valid and
then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.To_Object (False);
end if;
end;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Authenticate result from Facebook.
-- ------------------------------
procedure Authenticate (From : in out Facebook_Auth;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
use type Security.OAuth.Clients.Access_Token_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := F.Get_Session;
State : constant String := F.Get_Parameter (Security.OAuth.State);
Code : constant String := F.Get_Parameter (Security.OAuth.Code);
begin
Log.Info ("Auth code {0} for state {1}", Code, State);
if Session.Is_Valid then
if From.Is_Valid_State (Session.Get_Id, State) then
declare
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= From.Request_Access_Token (Code);
begin
if Acc /= null then
Log.Info ("Access token is {0}", Acc.Get_Name);
Session.Set_Attribute ("access_token",
Util.Beans.Objects.To_Object (Acc.Get_Name));
end if;
end;
end if;
end if;
end Authenticate;
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth,
Method => Authenticate,
Name => "authenticate");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Authenticate_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Facebook_Auth)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
begin
Friend_Map.Add_Default_Mapping;
Friend_Vector_Map.Set_Mapping (Friend_Map'Access);
Feed_Map.Add_Mapping ("id", FIELD_ID);
Feed_Map.Add_Mapping ("name", FIELD_NAME);
Feed_Map.Add_Mapping ("message", FIELD_MESSAGE);
Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION);
Feed_Map.Add_Mapping ("from/name", FIELD_FROM);
Feed_Map.Add_Mapping ("picture", FIELD_PICTURE);
Feed_Map.Add_Mapping ("link", FIELD_LINK);
Feed_Map.Add_Mapping ("icon", FIELD_ICON);
Feed_Vector_Map.Set_Mapping (Feed_Map'Access);
end Facebook;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
3a6bbc90945383fb8a397dfea518d66e88de7090
|
src/util-dates-formats.ads
|
src/util-dates-formats.ads
|
-----------------------------------------------------------------------
-- util-dates-formats -- Date Format ala strftime
-- Copyright (C) 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
-- == Localized date formatting ==
-- The `Util.Dates.Formats` provides a date formatting operation similar to the
-- Unix `strftime` or the `GNAT.Calendar.Time_IO`. The localization of month
-- and day labels is however handled through `Util.Properties.Bundle` (similar to
-- the Java world). Unlike `strftime`, this allows to have a multi-threaded application
-- that reports dates in several languages. The `GNAT.Calendar.Time_IO` only supports
-- English and this is the reason why it is not used here.
--
-- The date pattern recognizes the following formats:
--
-- | Format | Description |
-- | --- | ---------- |
-- | %a | The abbreviated weekday name according to the current locale.
-- | %A | The full weekday name according to the current locale.
-- | %b | The abbreviated month name according to the current locale.
-- | %h | Equivalent to %b. (SU)
-- | %B | The full month name according to the current locale.
-- | %c | The preferred date and time representation for the current locale.
-- | %C | The century number (year/100) as a 2-digit integer. (SU)
-- | %d | The day of the month as a decimal number (range 01 to 31).
-- | %D | Equivalent to %m/%d/%y
-- | %e | Like %d, the day of the month as a decimal number,
-- | | but a leading zero is replaced by a space. (SU)
-- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99)
-- | %G | The ISO 8601 week-based year
-- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23).
-- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12).
-- | %j | The day of the year as a decimal number (range 001 to 366).
-- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23);
-- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12);
-- | %m | The month as a decimal number (range 01 to 12).
-- | %M | The minute as a decimal number (range 00 to 59).
-- | %n | A newline character. (SU)
-- | %p | Either "AM" or "PM"
-- | %P | Like %p but in lowercase: "am" or "pm"
-- | %r | The time in a.m. or p.m. notation.
-- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU)
-- | %R | The time in 24 hour notation (%H:%M).
-- | %s | The number of seconds since the Epoch, that is,
-- | | since 1970\-01\-01 00:00:00 UTC. (TZ)
-- | %S | The second as a decimal number (range 00 to 60).
-- | %t | A tab character. (SU)
-- | %T | The time in 24 hour notation (%H:%M:%S). (SU)
-- | %u | The day of the week as a decimal, range 1 to 7,
-- | | Monday being 1. See also %w. (SU)
-- | %U | The week number of the current year as a decimal
-- | | number, range 00 to 53
-- | %V | The ISO 8601 week number
-- | %w | The day of the week as a decimal, range 0 to 6,
-- | | Sunday being 0. See also %u.
-- | %W | The week number of the current year as a decimal number,
-- | | range 00 to 53
-- | %x | The preferred date representation for the current locale
-- | | without the time.
-- | %X | The preferred time representation for the current locale
-- | | without the date.
-- | %y | The year as a decimal number without a century (range 00 to 99).
-- | %Y | The year as a decimal number including the century.
-- | %z | The timezone as hour offset from GMT.
-- | %Z | The timezone or name or abbreviation.
--
-- The following strftime flags are ignored:
--
-- | Format | Description |
-- | --- | ---------- |
-- | %E | Modifier: use alternative format, see below. (SU)
-- | %O | Modifier: use alternative format, see below. (SU)
--
-- SU: Single Unix Specification
-- C99: C99 standard, POSIX.1-2001
--
-- See strftime (3) manual page
--
-- To format and use the localize date, it is first necessary to get a bundle
-- for the `dates` so that date elements are translated into the given locale.
--
-- Factory : Util.Properties.Bundles.Loader;
-- Bundle : Util.Properties.Bundles.Manager;
-- ...
-- Load_Bundle (Factory, "dates", "fr", Bundle);
--
-- The date is formatted according to the pattern string described above.
-- The bundle is used by the formatter to use the day and month names in the
-- expected locale.
--
-- Date : String := Util.Dates.Formats.Format (Pattern => Pattern,
-- Date => Ada.Calendar.Clock,
-- Bundle => Bundle);
package Util.Dates.Formats is
-- Month labels.
MONTH_NAME_PREFIX : constant String := "util.month";
-- Day labels.
DAY_NAME_PREFIX : constant String := "util.day";
-- Short month/day suffix.
SHORT_SUFFIX : constant String := ".short";
-- Long month/day suffix.
LONG_SUFFIX : constant String := ".long";
-- The date time pattern name to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date time pattern.
DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern";
-- The default date pattern for %c (English).
DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y";
-- The date pattern to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date pattern.
DATE_LOCALE_NAME : constant String := "util.date.pattern";
-- The default date pattern for %x (English).
DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y";
-- The time pattern to be used for the %X representation.
-- This property name is searched in the bundle to find the localized time pattern.
TIME_LOCALE_NAME : constant String := "util.time.pattern";
-- The default time pattern for %X (English).
TIME_DEFAULT_PATTERN : constant String := "%T %Y";
AM_NAME : constant String := "util.date.am";
PM_NAME : constant String := "util.date.pm";
AM_DEFAULT : constant String := "AM";
PM_DEFAULT : constant String := "PM";
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- The date pattern is similar to the Unix <b>strftime</b> operation.
--
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Date_Record;
Bundle : in Util.Properties.Manager'Class);
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class);
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class) return String;
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Month : in Ada.Calendar.Month_Number;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Day : in Ada.Calendar.Formatting.Day_Name;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append a number with padding if necessary
procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Natural;
Padding : in Character;
Length : in Natural := 2);
-- Append the timezone offset
procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Offset : in Ada.Calendar.Time_Zones.Time_Offset);
end Util.Dates.Formats;
|
-----------------------------------------------------------------------
-- util-dates-formats -- Date Format ala strftime
-- Copyright (C) 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
-- == Localized date formatting ==
-- The `Util.Dates.Formats` provides a date formatting and parsing operation similar to the
-- Unix `strftime`, `strptime` or the `GNAT.Calendar.Time_IO`. The localization of month
-- and day labels is however handled through `Util.Properties.Bundle` (similar to
-- the Java world). Unlike `strftime` and `strptime`, this allows to have a multi-threaded
-- application that reports dates in several languages. The `GNAT.Calendar.Time_IO` only
-- supports English and this is the reason why it is not used here.
--
-- The date pattern recognizes the following formats:
--
-- | Format | Description |
-- | --- | ---------- |
-- | %a | The abbreviated weekday name according to the current locale.
-- | %A | The full weekday name according to the current locale.
-- | %b | The abbreviated month name according to the current locale.
-- | %h | Equivalent to %b. (SU)
-- | %B | The full month name according to the current locale.
-- | %c | The preferred date and time representation for the current locale.
-- | %C | The century number (year/100) as a 2-digit integer. (SU)
-- | %d | The day of the month as a decimal number (range 01 to 31).
-- | %D | Equivalent to %m/%d/%y
-- | %e | Like %d, the day of the month as a decimal number,
-- | | but a leading zero is replaced by a space. (SU)
-- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99)
-- | %G | The ISO 8601 week-based year
-- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23).
-- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12).
-- | %j | The day of the year as a decimal number (range 001 to 366).
-- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23);
-- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12);
-- | %m | The month as a decimal number (range 01 to 12).
-- | %M | The minute as a decimal number (range 00 to 59).
-- | %n | A newline character. (SU)
-- | %p | Either "AM" or "PM"
-- | %P | Like %p but in lowercase: "am" or "pm"
-- | %r | The time in a.m. or p.m. notation.
-- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU)
-- | %R | The time in 24 hour notation (%H:%M).
-- | %s | The number of seconds since the Epoch, that is,
-- | | since 1970\-01\-01 00:00:00 UTC. (TZ)
-- | %S | The second as a decimal number (range 00 to 60).
-- | %t | A tab character. (SU)
-- | %T | The time in 24 hour notation (%H:%M:%S). (SU)
-- | %u | The day of the week as a decimal, range 1 to 7,
-- | | Monday being 1. See also %w. (SU)
-- | %U | The week number of the current year as a decimal
-- | | number, range 00 to 53
-- | %V | The ISO 8601 week number
-- | %w | The day of the week as a decimal, range 0 to 6,
-- | | Sunday being 0. See also %u.
-- | %W | The week number of the current year as a decimal number,
-- | | range 00 to 53
-- | %x | The preferred date representation for the current locale
-- | | without the time.
-- | %X | The preferred time representation for the current locale
-- | | without the date.
-- | %y | The year as a decimal number without a century (range 00 to 99).
-- | %Y | The year as a decimal number including the century.
-- | %z | The timezone as hour offset from GMT.
-- | %Z | The timezone or name or abbreviation.
--
-- The following strftime flags are ignored:
--
-- | Format | Description |
-- | --- | ---------- |
-- | %E | Modifier: use alternative format, see below. (SU)
-- | %O | Modifier: use alternative format, see below. (SU)
--
-- SU: Single Unix Specification
-- C99: C99 standard, POSIX.1-2001
--
-- See strftime (3) and strptime (3) manual page
--
-- To format and use the localize date, it is first necessary to get a bundle
-- for the `dates` so that date elements are translated into the given locale.
--
-- Factory : Util.Properties.Bundles.Loader;
-- Bundle : Util.Properties.Bundles.Manager;
-- ...
-- Load_Bundle (Factory, "dates", "fr", Bundle);
--
-- The date is formatted according to the pattern string described above.
-- The bundle is used by the formatter to use the day and month names in the
-- expected locale.
--
-- Date : String := Util.Dates.Formats.Format (Pattern => Pattern,
-- Date => Ada.Calendar.Clock,
-- Bundle => Bundle);
--
-- To parse a date according to a pattern and a localization, the same pattern string
-- and bundle can be used and the `Parse` function will return the date in split format.
--
-- Result : Date_Record := Util.Dates.Formats.Parse (Date => Date,
-- Pattern => Pattern,
-- Bundle => Bundle);
--
package Util.Dates.Formats is
-- Month labels.
MONTH_NAME_PREFIX : constant String := "util.month";
-- Day labels.
DAY_NAME_PREFIX : constant String := "util.day";
-- Short month/day suffix.
SHORT_SUFFIX : constant String := ".short";
-- Long month/day suffix.
LONG_SUFFIX : constant String := ".long";
-- The date time pattern name to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date time pattern.
DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern";
-- The default date pattern for %c (English).
DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y";
-- The date pattern to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date pattern.
DATE_LOCALE_NAME : constant String := "util.date.pattern";
-- The default date pattern for %x (English).
DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y";
-- The time pattern to be used for the %X representation.
-- This property name is searched in the bundle to find the localized time pattern.
TIME_LOCALE_NAME : constant String := "util.time.pattern";
-- The default time pattern for %X (English).
TIME_DEFAULT_PATTERN : constant String := "%T %Y";
AM_NAME : constant String := "util.date.am";
PM_NAME : constant String := "util.date.pm";
AM_DEFAULT : constant String := "AM";
PM_DEFAULT : constant String := "PM";
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- The date pattern is similar to the Unix <b>strftime</b> operation.
--
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Date_Record;
Bundle : in Util.Properties.Manager'Class);
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class);
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class) return String;
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Month : in Ada.Calendar.Month_Number;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Day : in Ada.Calendar.Formatting.Day_Name;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append a number with padding if necessary
procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Natural;
Padding : in Character;
Length : in Natural := 2);
-- Append the timezone offset
procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Offset : in Ada.Calendar.Time_Zones.Time_Offset);
-- Parse the date according to the pattern and the given locale bundle and
-- return the data split record.
-- A `Constraint_Error` exception is raised if the date string is not in the correct format.
function Parse (Date : in String;
Pattern : in String;
Bundle : in Util.Properties.Manager'Class) return Date_Record;
end Util.Dates.Formats;
|
Declare the Parse function to parse a date using a pattern and a locale
|
Declare the Parse function to parse a date using a pattern and a locale
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
578659db4d4da6fa28aa8e96390918e27e37e158
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.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.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.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.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with 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;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.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.Counters.Modules.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.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.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.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.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.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.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, 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.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.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.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.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with 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;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.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.Counters.Modules.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.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.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.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.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.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.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;
|
Remove the wiki unit tests that have been moved to Ada Wiki
|
Remove the wiki unit tests that have been moved to Ada Wiki
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e1864b3b12f3c6d465b82b6d09c3c8e9830b21ce
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the <w:like> component in the factory
|
Add the <w:like> component in the factory
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
73030470a0655719209771ec6c651a66b989109e
|
src/gen-artifacts-distribs-bundles.adb
|
src/gen-artifacts-distribs-bundles.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name, Item : in Util.Properties.Value);
procedure Save_Property (Name, Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name, Item : in Util.Properties.Value) is
begin
Merge.Set (Name, Item);
end Merge_Property;
procedure Save_Property (Name, Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name));
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Open (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name, Item : in Util.Properties.Value);
procedure Save_Property (Name, Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name, Item : in Util.Properties.Value) is
begin
Merge.Set (Name, Item);
end Merge_Property;
procedure Save_Property (Name, Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name));
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
Fix creation of target bundle file
|
Fix creation of target bundle file
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
a415ff3e29314d24036998ba997c10840f7f2488
|
mat/src/mat-targets.ads
|
mat/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is recieved.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type);
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is tagged limited record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
end record;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is recieved.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is tagged limited record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
end record;
end MAT.Targets;
|
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
|
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
92c946d46841a63c6866654c3499f7b374bb246c
|
awa/plugins/awa-questions/src/awa-questions-modules.adb
|
awa/plugins/awa-questions/src/awa-questions-modules.adb
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Characters.Conversions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Wikis.Parsers;
with AWA.Wikis.Writers;
with ADO.Sessions;
with ADO.Statements;
with Util.Log.Loggers;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Questions.Beans;
with AWA.Applications;
package body AWA.Questions.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module");
package Register is new AWA.Modules.Beans (Module => Question_Module,
Module_Access => Question_Module_Access);
-- ------------------------------
-- Initialize the questions module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the questions module");
-- Setup the resource bundles.
App.Register ("questionMsg", "questions");
-- Edit and save a question.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
-- Edit and save an answer.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Answer_Bean",
Handler => AWA.Questions.Beans.Create_Answer_Bean'Access);
-- List of questions.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_List_Bean",
Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access);
-- Display a question with its answers.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Display_Bean",
Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the questions module.
-- ------------------------------
function Get_Question_Module return Question_Module_Access is
function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME);
begin
return Get;
end Get_Question_Module;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Ctx.Start;
if Question.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id));
WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace);
else
Log.Info ("Creating new question {0}", String '(Question.Get_Title));
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission,
Entity => WS);
Question.Set_Workspace (WS);
Question.Set_Author (User);
end if;
declare
Text : constant String := AWA.Wikis.Writers.To_Text (To_Wide (Question.Get_Description),
AWA.Wikis.Parsers.SYNTAX_MIX);
Last : Natural;
begin
if Text'Length < SHORT_DESCRIPTION_LENGTH then
Last := Text'Last;
else
Last := SHORT_DESCRIPTION_LENGTH;
end if;
Question.Set_Short_Description (Text (Text'First .. Last) & "...");
end;
if not Question.Is_Inserted then
Question.Set_Create_Date (Ada.Calendar.Clock);
else
Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Question.Save (DB);
Ctx.Commit;
end Save_Question;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given question.
AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission,
Entity => Question);
-- Before deleting the question, delete the associated answers.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE);
begin
Stmt.Set_Filter (Filter => "question_id = ?");
Stmt.Add_Param (Value => Question);
Stmt.Execute;
end;
Question.Delete (DB);
Ctx.Commit;
end Delete_Question;
-- ------------------------------
-- Load the question.
-- ------------------------------
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Question.Load (DB, Id, Found);
end Load_Question;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
if Answer.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id));
else
Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission,
Entity => Question);
Answer.Set_Author (User);
end if;
if not Answer.Is_Inserted then
Answer.Set_Create_Date (Ada.Calendar.Clock);
Answer.Set_Question (Question);
else
Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock,
Is_Null => False));
end if;
Answer.Save (DB);
Ctx.Commit;
end Save_Answer;
-- ------------------------------
-- Delete the answer.
-- ------------------------------
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission,
Entity => Answer);
Answer.Delete (DB);
Ctx.Commit;
end Delete_Answer;
-- ------------------------------
-- Load the answer.
-- ------------------------------
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Answer.Load (DB, Id, Found);
Question := Answer.Get_Question;
end Load_Answer;
end AWA.Questions.Modules;
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Characters.Conversions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with Wiki.Parsers;
with Wiki.Utils;
with ADO.Sessions;
with ADO.Statements;
with Util.Log.Loggers;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Questions.Beans;
with AWA.Applications;
package body AWA.Questions.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module");
package Register is new AWA.Modules.Beans (Module => Question_Module,
Module_Access => Question_Module_Access);
-- ------------------------------
-- Initialize the questions module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the questions module");
-- Setup the resource bundles.
App.Register ("questionMsg", "questions");
-- Edit and save a question.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
-- Edit and save an answer.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Answer_Bean",
Handler => AWA.Questions.Beans.Create_Answer_Bean'Access);
-- List of questions.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_List_Bean",
Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access);
-- Display a question with its answers.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Display_Bean",
Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the questions module.
-- ------------------------------
function Get_Question_Module return Question_Module_Access is
function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME);
begin
return Get;
end Get_Question_Module;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Ctx.Start;
if Question.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id));
WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace);
else
Log.Info ("Creating new question {0}", String '(Question.Get_Title));
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission,
Entity => WS);
Question.Set_Workspace (WS);
Question.Set_Author (User);
end if;
declare
Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description),
Wiki.Parsers.SYNTAX_MIX);
Last : Natural;
begin
if Text'Length < SHORT_DESCRIPTION_LENGTH then
Last := Text'Last;
else
Last := SHORT_DESCRIPTION_LENGTH;
end if;
Question.Set_Short_Description (Text (Text'First .. Last) & "...");
end;
if not Question.Is_Inserted then
Question.Set_Create_Date (Ada.Calendar.Clock);
else
Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Question.Save (DB);
Ctx.Commit;
end Save_Question;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given question.
AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission,
Entity => Question);
-- Before deleting the question, delete the associated answers.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE);
begin
Stmt.Set_Filter (Filter => "question_id = ?");
Stmt.Add_Param (Value => Question);
Stmt.Execute;
end;
Question.Delete (DB);
Ctx.Commit;
end Delete_Question;
-- ------------------------------
-- Load the question.
-- ------------------------------
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Question.Load (DB, Id, Found);
end Load_Question;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
if Answer.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id));
else
Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission,
Entity => Question);
Answer.Set_Author (User);
end if;
if not Answer.Is_Inserted then
Answer.Set_Create_Date (Ada.Calendar.Clock);
Answer.Set_Question (Question);
else
Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock,
Is_Null => False));
end if;
Answer.Save (DB);
Ctx.Commit;
end Save_Answer;
-- ------------------------------
-- Delete the answer.
-- ------------------------------
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission,
Entity => Answer);
Answer.Delete (DB);
Ctx.Commit;
end Delete_Answer;
-- ------------------------------
-- Load the answer.
-- ------------------------------
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Answer.Load (DB, Id, Found);
Question := Answer.Get_Question;
end Load_Answer;
end AWA.Questions.Modules;
|
Update to use the Wiki.Utils operations provided by Ada Wiki library
|
Update to use the Wiki.Utils operations provided by Ada Wiki library
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c578ed031cf4b40f0e740edda932c102186d147c
|
awa/plugins/awa-questions/src/awa-questions-modules.ads
|
awa/plugins/awa-questions/src/awa-questions-modules.ads
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with AWA.Modules;
with AWA.Questions.Services;
package AWA.Questions.Modules is
-- The name under which the module is registered.
NAME : constant String := "questions";
-- ------------------------------
-- Module questions
-- ------------------------------
type Question_Module is new AWA.Modules.Module with private;
type Question_Module_Access is access all Question_Module'Class;
-- Initialize the questions module.
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the question manager.
function Get_Question_Manager (Plugin : in Question_Module)
return Services.Question_Service_Access;
-- Create a question manager. This operation can be overridden to provide another
-- question service implementation.
function Create_Question_Manager (Plugin : in Question_Module)
return Services.Question_Service_Access;
-- Get the questions module.
function Get_Question_Module return Question_Module_Access;
-- Get the question manager instance associated with the current application.
function Get_Question_Manager return Services.Question_Service_Access;
private
type Question_Module is new AWA.Modules.Module with record
Manager : AWA.Questions.Services.Question_Service_Access;
end record;
end AWA.Questions.Modules;
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Questions.Models;
package AWA.Questions.Modules is
-- The name under which the module is registered.
NAME : constant String := "questions";
-- Define the permissions.
package ACL_Create_Questions is new Security.Permissions.Definition ("question-create");
package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete");
package ACL_Update_Questions is new Security.Permissions.Definition ("question-update");
package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create");
package ACL_Delete_Answer is new Security.Permissions.Definition ("answer-delete");
-- The maximum length for a short description.
SHORT_DESCRIPTION_LENGTH : constant Positive := 200;
-- ------------------------------
-- Module questions
-- ------------------------------
type Question_Module is new AWA.Modules.Module with private;
type Question_Module_Access is access all Question_Module'Class;
-- Initialize the questions module.
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the questions module.
function Get_Question_Module return Question_Module_Access;
-- Create or save the question.
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Delete the question.
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Load the question.
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier);
-- Create or save the answer.
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Delete the answer.
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Load the answer.
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier);
private
type Question_Module is new AWA.Modules.Module with null record;
end AWA.Questions.Modules;
|
Move the question services in the question module (simplify the implementation)
|
Move the question services in the question module (simplify the implementation)
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1dcf7faf438a5723f066f6f2fe83bac7105c54ab
|
awa/plugins/awa-storages/src/awa-storages-stores-files.ads
|
awa/plugins/awa-storages/src/awa-storages-stores-files.ads
|
-----------------------------------------------------------------------
-- awa-storages-stores-files -- File system store
-- 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 ADO.Sessions;
with ASF.Applications.Main.Configs;
with AWA.Storages.Models;
-- === File System store ===
-- The `AWA.Storages.Stores.Files` store uses the file system to save a data content.
-- Files are stored in a directory tree whose path is created from the workspace identifier
-- and the storage identifier. The layout is such that files belonged to a given workspace
-- are stored in the same directory sub-tree.
--
-- The root directory of the file system store is configured through the
-- <b>storage_root</b> and <b>tmp_storage_root</b> configuration properties.
package AWA.Storages.Stores.Files is
-- Parameter that indicates the root directory for the file storage.
package Root_Directory_Parameter is
new ASF.Applications.Main.Configs.Parameter (Name => "storage_root",
Default => "storage");
-- Parameter that indicates the root directory for a temporary file storage.
package Tmp_Directory_Parameter is
new ASF.Applications.Main.Configs.Parameter (Name => "tmp_storage_root",
Default => "tmp");
-- ------------------------------
-- Storage Service
-- ------------------------------
type File_Store (Len : Natural) is new AWA.Storages.Stores.Store with private;
type File_Store_Access is access all File_Store'Class;
-- Create a file storage service and use the <tt>Root</tt> directory to store the files.
function Create_File_Store (Root : in String) return Store_Access;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String);
-- Load the storage item represented by `From` in a file that can be accessed locally.
procedure Load (Storage : in File_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File);
-- Create a storage
procedure Create (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File);
-- Delete the content associate with the storage represented by `From`.
procedure Delete (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class);
-- Build a path where the file store represented by <tt>Store</tt> is saved.
function Get_Path (Storage : in File_Store;
Store : in AWA.Storages.Models.Storage_Ref'Class) return String;
private
type File_Store (Len : Natural) is new AWA.Storages.Stores.Store with record
-- The root directory that contains the file system storage.
Root : String (1 .. Len);
end record;
end AWA.Storages.Stores.Files;
|
-----------------------------------------------------------------------
-- awa-storages-stores-files -- File system store
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ASF.Applications.Main.Configs;
with AWA.Storages.Models;
-- === File System store ===
-- The `AWA.Storages.Stores.Files` store uses the file system to save a data content.
-- Files are stored in a directory tree whose path is created from the workspace identifier
-- and the storage identifier. The layout is such that files belonged to a given workspace
-- are stored in the same directory sub-tree.
--
-- The root directory of the file system store is configured through the
-- <b>storage_root</b> and <b>tmp_storage_root</b> configuration properties.
package AWA.Storages.Stores.Files is
-- Parameter that indicates the root directory for the file storage.
package Root_Directory_Parameter is
new ASF.Applications.Main.Configs.Parameter (Name => "storage_root",
Default => "storage");
-- Parameter that indicates the root directory for a temporary file storage.
package Tmp_Directory_Parameter is
new ASF.Applications.Main.Configs.Parameter (Name => "tmp_storage_root",
Default => "tmp");
-- ------------------------------
-- Storage Service
-- ------------------------------
type File_Store (Len : Natural) is new AWA.Storages.Stores.Store with private;
type File_Store_Access is access all File_Store'Class;
-- Create a file storage service and use the <tt>Root</tt> directory to store the files.
function Create_File_Store (Root : in String) return Store_Access;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String);
-- Load the storage item represented by `From` in a file that can be accessed locally.
procedure Load (Storage : in File_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File);
-- Create a storage
procedure Create (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File);
-- Delete the content associate with the storage represented by `From`.
procedure Delete (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class);
-- Build a path where the file store represented by <tt>Store</tt> is saved.
function Get_Path (Storage : in File_Store;
Store : in AWA.Storages.Models.Storage_Ref'Class) return String;
-- Build a path where the file store represented by <tt>Store</tt> is saved.
function Get_Path (Storage : in File_Store;
Workspace_Id : in ADO.Identifier;
File_Id : in ADO.Identifier) return String;
private
type File_Store (Len : Natural) is new AWA.Storages.Stores.Store with record
-- The root directory that contains the file system storage.
Root : String (1 .. Len);
end record;
end AWA.Storages.Stores.Files;
|
Declare a new Get_Path function to build a temporary file path
|
Declare a new Get_Path function to build a temporary file path
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
75eb288b997d19c508e3fe69de8ed90aac24284b
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (0).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.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 := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_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.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
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;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (0).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.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 := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_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.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
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;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
Fix presentation
|
Fix presentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
48cf1478a4fbd04d42840a05ea2ac63976b165f4
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.ads
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.ads
|
-----------------------------------------------------------------------
-- awa-images-modules-tests -- Unit tests for image service
-- Copyright (C) 2012, 2013, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
with ADO;
package AWA.Images.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Id : ADO.Identifier;
Manager : AWA.Images.Modules.Image_Module_Access;
end record;
-- Test creation of a storage object
procedure Test_Create_Image (T : in out Test);
-- Test the Get_Sizes operation.
procedure Test_Get_Sizes (T : in out TesT);
end AWA.Images.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-images-modules-tests -- Unit tests for image service
-- Copyright (C) 2012, 2013, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
with ADO;
package AWA.Images.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Id : ADO.Identifier;
Manager : AWA.Images.Modules.Image_Module_Access;
end record;
-- Test creation of a storage object
procedure Test_Create_Image (T : in out Test);
-- Test the Get_Sizes operation.
procedure Test_Get_Sizes (T : in out Test);
-- Test the Scale operation.
procedure Test_Scale (T : in out Test);
end AWA.Images.Modules.Tests;
|
Declare the Test_Scale procedure
|
Declare the Test_Scale procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
fd7b2213e784c2f8a47f9931719e50c547f2d85f
|
src/babel-files.ads
|
src/babel-files.ads
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Systems.Types;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
subtype File_Mode is Util.Systems.Types.mode_t;
-- type File_Mode is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Compare two files on their name and directory.
function "<" (Left, Right : in File_Type) return Boolean;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Return true if the file is a new file.
function Is_New (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Set the owner and group of the file.
procedure Set_Owner (Element : in File_Type;
User : in Uid_Type;
Group : in Gid_Type);
-- Set the file modification date.
procedure Set_Date (Element : in File_Type;
Date : in Util.Systems.Types.Timespec);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
-- Return the file size.
function Get_Size (Element : in File_Type) return File_Size;
-- Return the file modification date.
function Get_Date (Element : in File_Type) return Ada.Calendar.Time;
-- Return the user uid.
function Get_User (Element : in File_Type) return Uid_Type;
-- Return the group gid.
function Get_Group (Element : in File_Type) return Gid_Type;
-- Return the file unix mode.
function Get_Mode (Element : in File_Type) return File_Mode;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Set the directory object associated with the container.
procedure Set_Directory (Into : in out File_Container;
Directory : in Directory_Type) is abstract;
-- Execute the Process procedure on each directory found in the container.
procedure Each_Directory (Container : in File_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is abstract;
-- Execute the Process procedure on each file found in the container.
procedure Each_File (Container : in File_Container;
Process : not null access
procedure (F : in File_Type)) is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
-- Set the directory object associated with the container.
overriding
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type);
-- Execute the Process procedure on each directory found in the container.
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type));
-- Execute the Process procedure on each file found in the container.
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type));
private
type File_Type is access all File;
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type Directory_Type is access all Directory;
package File_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => File_Type,
"=" => "=");
package Directory_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_Type,
"=" => "=");
subtype Directory_Vector is Directory_Vectors.Vector;
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
Files : File_Vectors.Vector;
Dirs : Directory_Vectors.Vector;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Systems.Types;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
subtype File_Mode is Util.Systems.Types.mode_t;
-- type File_Mode is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Compare two files on their name and directory.
function "<" (Left, Right : in File_Type) return Boolean;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Return true if the file is a new file.
function Is_New (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Set the owner and group of the file.
procedure Set_Owner (Element : in File_Type;
User : in Uid_Type;
Group : in Gid_Type);
-- Set the file modification date.
procedure Set_Date (Element : in File_Type;
Date : in Util.Systems.Types.Timespec);
procedure Set_Date (Element : in File_Type;
Date : in Ada.Calendar.Time);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
-- Return the file size.
function Get_Size (Element : in File_Type) return File_Size;
-- Return the file modification date.
function Get_Date (Element : in File_Type) return Ada.Calendar.Time;
-- Return the user uid.
function Get_User (Element : in File_Type) return Uid_Type;
-- Return the group gid.
function Get_Group (Element : in File_Type) return Gid_Type;
-- Return the file unix mode.
function Get_Mode (Element : in File_Type) return File_Mode;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Set the directory object associated with the container.
procedure Set_Directory (Into : in out File_Container;
Directory : in Directory_Type) is abstract;
-- Execute the Process procedure on each directory found in the container.
procedure Each_Directory (Container : in File_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is abstract;
-- Execute the Process procedure on each file found in the container.
procedure Each_File (Container : in File_Container;
Process : not null access
procedure (F : in File_Type)) is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
-- Set the directory object associated with the container.
overriding
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type);
-- Execute the Process procedure on each directory found in the container.
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type));
-- Execute the Process procedure on each file found in the container.
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type));
private
type String_Access is access all String;
type File_Type is access all File;
type Directory is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
-- Name : aliased String (1 .. Len);
Name_Pos : Natural := 0;
Name : String_Access;
end record;
type Directory_Type is access all Directory;
package File_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => File_Type,
"=" => "=");
package Directory_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_Type,
"=" => "=");
subtype Directory_Vector is Directory_Vectors.Vector;
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
Files : File_Vectors.Vector;
Dirs : Directory_Vectors.Vector;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
Declare the Set_Date procedure Declare the String_Access Use a String_Access to store the directory's path
|
Declare the Set_Date procedure
Declare the String_Access
Use a String_Access to store the directory's path
|
Ada
|
apache-2.0
|
stcarrez/babel
|
1a4d532baf144fd9dd1a0b8e99bb5969ea721bb1
|
src/el-contexts.ads
|
src/el-contexts.ads
|
-----------------------------------------------------------------------
-- EL.Contexts -- Contexts for evaluating an expression
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The expression context provides information to resolve runtime
-- information when evaluating an expression. The context provides
-- a resolver whose role is to find variables given their name.
with EL.Objects;
with Util.Beans.Basic;
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with EL.Functions;
limited with EL.Variables;
package EL.Contexts is
pragma Preelaborate;
use EL.Objects;
use Ada.Strings.Unbounded;
type ELContext;
-- ------------------------------
-- Expression Resolver
-- ------------------------------
-- Enables customization of variable and property resolution
-- behavior for EL expression evaluation.
type ELResolver is interface;
type ELResolver_Access is access all ELResolver'Class;
-- Get the value associated with a base object and a given property.
function Get_Value (Resolver : ELResolver;
Context : ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return EL.Objects.Object is abstract;
-- Set the value associated with a base object and a given property.
procedure Set_Value (Resolver : in out ELResolver;
Context : in ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- Expression Context
-- ------------------------------
-- Context information for expression evaluation.
type ELContext is limited interface;
type ELContext_Access is access all ELContext'Class;
-- Retrieves the ELResolver associated with this ELcontext.
function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract;
-- Retrieves the VariableMapper associated with this ELContext.
function Get_Variable_Mapper (Context : ELContext)
return access EL.Variables.Variable_Mapper'Class is abstract;
-- Set the variable mapper associated with this ELContext.
procedure Set_Variable_Mapper (Context : in out ELContext;
Mapper : access EL.Variables.Variable_Mapper'Class)
is abstract;
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
function Get_Function_Mapper (Context : ELContext)
return EL.Functions.Function_Mapper_Access is abstract;
-- Set the function mapper associated with this ELContext.
procedure Set_Function_Mapper (Context : in out ELContext;
Mapper : access EL.Functions.Function_Mapper'Class)
is abstract;
-- Handle the exception during expression evaluation. The handler can ignore the
-- exception or raise it.
procedure Handle_Exception (Context : in ELContext;
Ex : in Ada.Exceptions.Exception_Occurrence) is abstract;
end EL.Contexts;
|
-----------------------------------------------------------------------
-- EL.Contexts -- Contexts for evaluating an expression
-- 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.
-----------------------------------------------------------------------
-- The expression context provides information to resolve runtime
-- information when evaluating an expression. The context provides
-- a resolver whose role is to find variables given their name.
with EL.Objects;
with Util.Beans.Basic;
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with EL.Functions;
limited with EL.Variables;
package EL.Contexts is
pragma Preelaborate;
use EL.Objects;
use Ada.Strings.Unbounded;
type ELContext;
-- ------------------------------
-- Expression Resolver
-- ------------------------------
-- Enables customization of variable and property resolution
-- behavior for EL expression evaluation.
type ELResolver is limited interface;
type ELResolver_Access is access all ELResolver'Class;
-- Get the value associated with a base object and a given property.
function Get_Value (Resolver : ELResolver;
Context : ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return EL.Objects.Object is abstract;
-- Set the value associated with a base object and a given property.
procedure Set_Value (Resolver : in out ELResolver;
Context : in ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- Expression Context
-- ------------------------------
-- Context information for expression evaluation.
type ELContext is limited interface;
type ELContext_Access is access all ELContext'Class;
-- Retrieves the ELResolver associated with this ELcontext.
function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract;
-- Retrieves the VariableMapper associated with this ELContext.
function Get_Variable_Mapper (Context : ELContext)
return access EL.Variables.Variable_Mapper'Class is abstract;
-- Set the variable mapper associated with this ELContext.
procedure Set_Variable_Mapper (Context : in out ELContext;
Mapper : access EL.Variables.Variable_Mapper'Class)
is abstract;
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
function Get_Function_Mapper (Context : ELContext)
return EL.Functions.Function_Mapper_Access is abstract;
-- Set the function mapper associated with this ELContext.
procedure Set_Function_Mapper (Context : in out ELContext;
Mapper : access EL.Functions.Function_Mapper'Class)
is abstract;
-- Handle the exception during expression evaluation. The handler can ignore the
-- exception or raise it.
procedure Handle_Exception (Context : in ELContext;
Ex : in Ada.Exceptions.Exception_Occurrence) is abstract;
end EL.Contexts;
|
Change the ELResolver to a limited interface
|
Change the ELResolver to a limited interface
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
1acbe1d58ef0ee41b9d7905be7b18bed1bc2a7dd
|
src/util-log-locations.ads
|
src/util-log-locations.ads
|
-----------------------------------------------------------------------
-- util-log-locations -- General purpose source file location
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
package Util.Log.Locations is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
-- Get the column number
function Column (Info : in Line_Info) return Natural;
-- Get the source file
function File (Info : in Line_Info) return String;
-- Create a source line information.
function Create_Line_Info (File : in File_Info_Access;
Line : in Natural;
Column : in Natural := 0) return Line_Info;
-- Get a printable representation of the line information using
-- the format:
-- <path>:<line>[:<column>]
-- The path can be reported as relative or absolute path.
-- The column is optional and reported by default.
function To_String (Info : in Line_Info;
Relative : in Boolean := True;
Column : in Boolean := True) return String;
private
pragma Inline (Line);
pragma Inline (File);
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end Util.Log.Locations;
|
-----------------------------------------------------------------------
-- util-log-locations -- General purpose source file location
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
package Util.Log.Locations is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
-- Get the column number
function Column (Info : in Line_Info) return Natural;
-- Get the source file
function File (Info : in Line_Info) return String;
-- Compare the two source location. The comparison is made on:
-- o the source file,
-- o the line number,
-- o the column.
function "<" (Left, Right : in Line_Info) return Boolean;
-- Create a source line information.
function Create_Line_Info (File : in File_Info_Access;
Line : in Natural;
Column : in Natural := 0) return Line_Info;
-- Get a printable representation of the line information using
-- the format:
-- <path>:<line>[:<column>]
-- The path can be reported as relative or absolute path.
-- The column is optional and reported by default.
function To_String (Info : in Line_Info;
Relative : in Boolean := True;
Column : in Boolean := True) return String;
private
pragma Inline (Line);
pragma Inline (File);
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end Util.Log.Locations;
|
Declare the "<" function to compare two source locations
|
Declare the "<" function to compare two source locations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
75baa9b76472b63a7a2a119922787c85014b5e5f
|
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;
Options : MAT.Commands.Options_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
begin
Target.Console (Console'Unchecked_Access);
MAT.Commands.Initialize_Options (Target, Options);
Server.Start (Options.Address);
MAT.Commands.Interactive (Target);
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Commands.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;
Options : MAT.Commands.Options_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
begin
Target.Console (Console'Unchecked_Access);
MAT.Commands.Initialize_Options (Target, Options);
MAT.Commands.Initialize_Files (Target);
Server.Start (Options.Address);
MAT.Commands.Interactive (Target);
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Commands.Usage_Error =>
Server.Stop;
end Matp;
|
Load the MAT files passed in the command line argument
|
Load the MAT files passed in the command line argument
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
821d77d4a81d73c04bd2377e105ef0fb61ce80ff
|
src/wiki-render.ads
|
src/wiki-render.ads
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering after complete wiki document nodes are rendered.
procedure Finish (Document : in out Renderer) is abstract;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document);
end Wiki.Render;
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering after complete wiki document nodes are rendered.
procedure Finish (Document : in out Renderer) is abstract;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document);
end Wiki.Render;
|
Change the Link_Renderer interface to use a Wide_Wide_String for the link
|
Change the Link_Renderer interface to use a Wide_Wide_String for the link
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
022f9a4e7f9ef99557c0bd039bb31b845767cdb0
|
examples/filesystem/src/main.adb
|
examples/filesystem/src/main.adb
|
with HAL; use HAL;
with Virtual_File_System; use Virtual_File_System;
with HAL.Filesystem; use HAL.Filesystem;
with Semihosting;
with Semihosting.Filesystem; use Semihosting.Filesystem;
with File_Block_Drivers; use File_Block_Drivers;
with Partitions; use Partitions;
procedure Main is
procedure List_Dir (FS : in out FS_Driver'Class;
Path : Pathname);
-- List files in directory
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname);
-- List partition in a disk file
--------------
-- List_Dir --
--------------
procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is
Status : Status_Kind;
DH : Directory_Handle_Ref;
begin
Status := FS.Open_Directory (Path, DH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img);
else
declare
Ent : Directory_Entry;
Index : Positive := 1;
begin
Semihosting.Log_Line ("Listing '" & Path & "' content:");
loop
Status := DH.Read_Entry (Index, Ent);
if Status = Status_Ok then
Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'");
Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img);
else
exit;
end if;
Index := Index + 1;
end loop;
end;
end if;
end List_Dir;
---------------------
-- List_Partitions --
---------------------
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname)
is
File : File_Handle_Ref;
begin
if FS.Open (Path_To_Disk_Image, Read_Only, File) /= Status_Ok then
Semihosting.Log_Line ("Cannot open disk image '" &
Path_To_Disk_Image & "'");
return;
end if;
declare
Disk : aliased File_Block_Driver (File);
Nbr : Natural;
P_Entry : Partition_Entry;
begin
Nbr := Number_Of_Partitions (Disk'Unchecked_Access);
Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " &
Nbr'Img & " parition(s)");
for Id in 1 .. Nbr loop
if Get_Partition_Entry (Disk'Unchecked_Access,
Id,
P_Entry) /= Status_Ok
then
Semihosting.Log_Line ("Cannot read partition :" & Id'Img);
else
Semihosting.Log_Line (" - partition :" & Id'Img);
Semihosting.Log_Line (" Status:" & P_Entry.Status'Img);
Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img);
Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img);
Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img);
end if;
end loop;
end;
end List_Partitions;
My_VFS : VFS;
My_VFS2 : aliased VFS;
My_VFS3 : aliased VFS;
My_SHFS : aliased SHFS;
Status : Status_Kind;
FH : File_Handle_Ref;
Data : Byte_Array (1 .. 10);
begin
-- Mount My_VFS2 in My_VFS1
Status := My_VFS.Mount (Path => "vfs2",
Filesystem => My_VFS2'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount My_VFS3 in My_VFS2
Status := My_VFS2.Mount (Path => "vfs3",
Filesystem => My_VFS3'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount semi-hosting filesystem in My_VFS1
Status := My_VFS.Mount (Path => "host",
Filesystem => My_SHFS'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- List all partitions of a disk image on the host
List_Partitions (My_VFS, "/host/tmp/disk_8_partitions.img");
-- Try to unlink a file that doesn't exist in My_VFS2
Status := My_VFS.Unlink ("/vfs2/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Try to unlink a file that doesn't exist in My_VFS3
Status := My_VFS.Unlink ("/vfs2/vfs3/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Open a file on the host
Status := My_VFS.Open ("/host/tmp/test.shfs", Read_Only, FH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Error: " & Status'Img);
end if;
-- Read the first 10 characters
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
-- Move file cursor
Status := FH.Seek (10);
if Status /= Status_Ok then
Semihosting.Log_Line ("Seek Error: " & Status'Img);
end if;
-- Read 10 characters again
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
Status := FH.Close;
if Status /= Status_Ok then
Semihosting.Log_Line ("Close Error: " & Status'Img);
end if;
-- Test directory listing
List_Dir (My_VFS, "/");
List_Dir (My_VFS, "/vfs2");
List_Dir (My_VFS, "/vfs2/");
end Main;
|
with HAL; use HAL;
with Virtual_File_System; use Virtual_File_System;
with HAL.Filesystem; use HAL.Filesystem;
with Semihosting;
with Semihosting.Filesystem; use Semihosting.Filesystem;
with File_Block_Drivers; use File_Block_Drivers;
with Partitions; use Partitions;
procedure Main is
procedure List_Dir (FS : in out FS_Driver'Class;
Path : Pathname);
-- List files in directory
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname);
-- List partition in a disk file
--------------
-- List_Dir --
--------------
procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is
Status : Status_Kind;
DH : Directory_Handle_Ref;
begin
Status := FS.Open_Directory (Path, DH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img);
else
declare
Ent : Directory_Entry;
Index : Positive := 1;
begin
Semihosting.Log_Line ("Listing '" & Path & "' content:");
loop
Status := DH.Read_Entry (Index, Ent);
if Status = Status_Ok then
Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'");
Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img);
else
exit;
end if;
Index := Index + 1;
end loop;
end;
end if;
end List_Dir;
---------------------
-- List_Partitions --
---------------------
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname)
is
File : File_Handle_Ref;
begin
if FS.Open (Path_To_Disk_Image, Read_Only, File) /= Status_Ok then
Semihosting.Log_Line ("Cannot open disk image '" &
Path_To_Disk_Image & "'");
return;
end if;
declare
Disk : aliased File_Block_Driver (File);
Nbr : Natural;
P_Entry : Partition_Entry;
begin
Nbr := Number_Of_Partitions (Disk'Unchecked_Access);
Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " &
Nbr'Img & " parition(s)");
for Id in 1 .. Nbr loop
if Get_Partition_Entry (Disk'Unchecked_Access,
Id,
P_Entry) /= Status_Ok
then
Semihosting.Log_Line ("Cannot read partition :" & Id'Img);
else
Semihosting.Log_Line (" - partition :" & Id'Img);
Semihosting.Log_Line (" Status:" & P_Entry.Status'Img);
Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img);
Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img);
Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img);
end if;
end loop;
end;
end List_Partitions;
My_VFS : VFS;
My_VFS2 : aliased VFS;
My_VFS3 : aliased VFS;
My_SHFS : aliased SHFS;
Status : Status_Kind;
FH : File_Handle_Ref;
Data : Byte_Array (1 .. 10);
begin
-- Mount My_VFS2 in My_VFS
Status := My_VFS.Mount (Path => "vfs2",
Filesystem => My_VFS2'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount My_VFS3 in My_VFS2
Status := My_VFS2.Mount (Path => "vfs3",
Filesystem => My_VFS3'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount semi-hosting filesystem in My_VFS
Status := My_VFS.Mount (Path => "host",
Filesystem => My_SHFS'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- List all partitions of a disk image on the host
List_Partitions (My_VFS, "/host/tmp/disk_8_partitions.img");
-- Try to unlink a file that doesn't exist in My_VFS2
Status := My_VFS.Unlink ("/vfs2/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Try to unlink a file that doesn't exist in My_VFS3
Status := My_VFS.Unlink ("/vfs2/vfs3/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Open a file on the host
Status := My_VFS.Open ("/host/tmp/test.shfs", Read_Only, FH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Error: " & Status'Img);
end if;
-- Read the first 10 characters
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
-- Move file cursor
Status := FH.Seek (10);
if Status /= Status_Ok then
Semihosting.Log_Line ("Seek Error: " & Status'Img);
end if;
-- Read 10 characters again
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
Status := FH.Close;
if Status /= Status_Ok then
Semihosting.Log_Line ("Close Error: " & Status'Img);
end if;
-- Test directory listing
List_Dir (My_VFS, "/");
List_Dir (My_VFS, "/vfs2");
List_Dir (My_VFS, "/vfs2/");
end Main;
|
Fix typos
|
examples/filesystem: Fix typos
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
8b4b7f6f561d28ce38998400339bd88b0abc5895
|
src/gen-model-enums.ads
|
src/gen-model-enums.ads
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Mappings;
with Gen.Model.Packages;
package Gen.Model.Enums is
use Ada.Strings.Unbounded;
type Enum_Definition;
type Enum_Definition_Access is access all Enum_Definition'Class;
-- ------------------------------
-- Enum value definition
-- ------------------------------
type Value_Definition is new Definition with record
Number : Natural := 0;
Enum : Enum_Definition_Access;
end record;
type Value_Definition_Access is access all Value_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 : Value_Definition;
Name : String) return Util.Beans.Objects.Object;
package Value_List is new Gen.Model.List (T => Value_Definition,
T_Access => Value_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Enum_Definition is new Mappings.Mapping_Definition with record
Values : aliased Value_List.List_Definition;
Values_Bean : Util.Beans.Objects.Object;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
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 : Enum_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Enum_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Enum_Definition);
-- Add an enum value to this enum definition and return the new value.
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access);
-- Create an enum with the given name.
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access;
end Gen.Model.Enums;
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Mappings;
with Gen.Model.Packages;
package Gen.Model.Enums is
use Ada.Strings.Unbounded;
type Enum_Definition;
type Enum_Definition_Access is access all Enum_Definition'Class;
-- ------------------------------
-- Enum value definition
-- ------------------------------
type Value_Definition is new Definition with record
Number : Natural := 0;
Enum : Enum_Definition_Access;
end record;
type Value_Definition_Access is access all Value_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 : Value_Definition;
Name : String) return Util.Beans.Objects.Object;
package Value_List is new Gen.Model.List (T => Value_Definition,
T_Access => Value_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Enum_Definition is new Mappings.Mapping_Definition with record
Values : aliased Value_List.List_Definition;
Values_Bean : Util.Beans.Objects.Object;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Sql_Type : Unbounded_String;
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 : Enum_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Enum_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Enum_Definition);
-- Add an enum value to this enum definition and return the new value.
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access);
-- Create an enum with the given name.
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access;
end Gen.Model.Enums;
|
Add an sql type mapping for the enum
|
Add an sql type mapping for the enum
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
4ea30e8ba2c81650597141a24650ad9b2b6aacea
|
src/security-random.ads
|
src/security-random.ads
|
-----------------------------------------------------------------------
-- security-random -- Random numbers for nonce, secret keys, token generation
-- 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.Streams;
with Ada.Finalization;
with Ada.Strings.Unbounded;
private with Ada.Numerics.Discrete_Random;
private with Interfaces;
package Security.Random is
type Generator is limited new Ada.Finalization.Limited_Controlled with private;
-- Initialize the random generator.
overriding
procedure Initialize (Gen : in out Generator);
-- Fill the array with pseudo-random numbers.
procedure Generate (Gen : in out Generator;
Into : out Ada.Streams.Stream_Element_Array);
-- Generate a random sequence of bits and convert the result
-- into a string in base64url.
function Generate (Gen : in out Generator'Class;
Bits : in Positive) return String;
-- Generate a random sequence of bits, convert the result
-- into a string in base64url and append it to the buffer.
procedure Generate (Gen : in out Generator'Class;
Bits : in Positive;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
private
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
-- Protected type to allow using the random generator by several tasks.
protected type Raw_Generator is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array);
procedure Reset;
private
-- Random number generator used for ID generation.
Rand : Id_Random.Generator;
end Raw_Generator;
type Generator is limited new Ada.Finalization.Limited_Controlled with record
Rand : Raw_Generator;
end record;
end Security.Random;
|
-----------------------------------------------------------------------
-- security-random -- Random numbers for nonce, secret keys, token generation
-- 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.Streams;
with Ada.Finalization;
with Ada.Strings.Unbounded;
private with Ada.Numerics.Discrete_Random;
private with Interfaces;
-- == Random Generator ==
-- The <tt>Security.Random</tt> package defines the <tt>Generator</tt> tagged type
-- which provides operations to generate random tokens intended to be used for
-- a nonce, access token, salt or other purposes. The generator is intended to be
-- used in multi-task environments as it implements the low level random generation
-- within a protected type. The generator defines a <tt>Generate</tt> operation
-- that returns either a binary random array or the base64url encoding of the
-- binary array.
package Security.Random is
type Generator is limited new Ada.Finalization.Limited_Controlled with private;
-- Initialize the random generator.
overriding
procedure Initialize (Gen : in out Generator);
-- Fill the array with pseudo-random numbers.
procedure Generate (Gen : in out Generator;
Into : out Ada.Streams.Stream_Element_Array);
-- Generate a random sequence of bits and convert the result
-- into a string in base64url.
function Generate (Gen : in out Generator'Class;
Bits : in Positive) return String;
-- Generate a random sequence of bits, convert the result
-- into a string in base64url and append it to the buffer.
procedure Generate (Gen : in out Generator'Class;
Bits : in Positive;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
private
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
-- Protected type to allow using the random generator by several tasks.
protected type Raw_Generator is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array);
procedure Reset;
private
-- Random number generator used for ID generation.
Rand : Id_Random.Generator;
end Raw_Generator;
type Generator is limited new Ada.Finalization.Limited_Controlled with record
Rand : Raw_Generator;
end record;
end Security.Random;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
846e8eb39a89cd731441f54c2fab939af0b572ae
|
src/util-serialize-tools.adb
|
src/util-serialize-tools.adb
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- Copyright (C) 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.Containers;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array (Name => Name);
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Buffer : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Output.Initialize (Buffer'Unchecked_Access);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer));
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Mapper.Add_Mapping ("**", JSON_Mapping'Access);
Object_Mapper.Set_Context (Mapper, Context'Unchecked_Access);
Parser.Parse_String (Content, Mapper);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- Copyright (C) 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Util.Streams.Texts;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array (Name => Name);
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Buffer : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Output.Initialize (Buffer'Unchecked_Access);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Buffer);
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Mapper.Add_Mapping ("**", JSON_Mapping'Access);
Object_Mapper.Set_Context (Mapper, Context'Unchecked_Access);
Parser.Parse_String (Content, Mapper);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
Remove conversion to Buffered_Stream (not necessary anymore)
|
Remove conversion to Buffered_Stream (not necessary anymore)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
63b4b02c7b037c52387578c90957eab1cd0fdc11
|
samples/demo_server.adb
|
samples/demo_server.adb
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- 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.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Upload_Servlet;
with Countries;
with Volume;
with Messages;
with Facebook;
-- with Images;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Upload : aliased Upload_Servlet.Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Mapping (Name => "upload", Pattern => "upload.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
App.Register (Name => "image", Class => "Image_Bean", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Upload_Servlet;
with Countries;
with Volume;
with Messages;
with Facebook;
-- with Images;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Upload : aliased Upload_Servlet.Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Mapping (Name => "upload", Pattern => "upload.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
Fix error when the demo is started
|
Fix error when the demo is started
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
fad8929e07c94f9391212f8a96a4e761ee0d24b9
|
ARM/STM32/svd/stm32f429x/stm32_svd-i2c.ads
|
ARM/STM32/svd/stm32f429x/stm32_svd-i2c.ads
|
-- This spec has been automatically generated from STM32F429x.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
with HAL;
with System;
package STM32_SVD.I2C is
pragma Preelaborate;
---------------
-- Registers --
---------------
------------------
-- CR1_Register --
------------------
-- Control register 1
type CR1_Register is record
-- Peripheral enable
PE : Boolean := False;
-- SMBus mode
SMBUS : Boolean := False;
-- unspecified
Reserved_2_2 : HAL.Bit := 16#0#;
-- SMBus type
SMBTYPE : Boolean := False;
-- ARP enable
ENARP : Boolean := False;
-- PEC enable
ENPEC : Boolean := False;
-- General call enable
ENGC : Boolean := False;
-- Clock stretching disable (Slave mode)
NOSTRETCH : Boolean := False;
-- Start generation
START : Boolean := False;
-- Stop generation
STOP : Boolean := False;
-- Acknowledge enable
ACK : Boolean := False;
-- Acknowledge/PEC Position (for data reception)
POS : Boolean := False;
-- Packet error checking
PEC : Boolean := False;
-- SMBus alert
ALERT : Boolean := False;
-- unspecified
Reserved_14_14 : HAL.Bit := 16#0#;
-- Software reset
SWRST : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR1_Register use record
PE at 0 range 0 .. 0;
SMBUS at 0 range 1 .. 1;
Reserved_2_2 at 0 range 2 .. 2;
SMBTYPE at 0 range 3 .. 3;
ENARP at 0 range 4 .. 4;
ENPEC at 0 range 5 .. 5;
ENGC at 0 range 6 .. 6;
NOSTRETCH at 0 range 7 .. 7;
START at 0 range 8 .. 8;
STOP at 0 range 9 .. 9;
ACK at 0 range 10 .. 10;
POS at 0 range 11 .. 11;
PEC at 0 range 12 .. 12;
ALERT at 0 range 13 .. 13;
Reserved_14_14 at 0 range 14 .. 14;
SWRST at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- CR2_Register --
------------------
subtype CR2_FREQ_Field is HAL.UInt6;
-- Control register 2
type CR2_Register is record
-- Peripheral clock frequency
FREQ : CR2_FREQ_Field := 16#0#;
-- unspecified
Reserved_6_7 : HAL.UInt2 := 16#0#;
-- Error interrupt enable
ITERREN : Boolean := False;
-- Event interrupt enable
ITEVTEN : Boolean := False;
-- Buffer interrupt enable
ITBUFEN : Boolean := False;
-- DMA requests enable
DMAEN : Boolean := False;
-- DMA last transfer
LAST : Boolean := False;
-- unspecified
Reserved_13_31 : HAL.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR2_Register use record
FREQ at 0 range 0 .. 5;
Reserved_6_7 at 0 range 6 .. 7;
ITERREN at 0 range 8 .. 8;
ITEVTEN at 0 range 9 .. 9;
ITBUFEN at 0 range 10 .. 10;
DMAEN at 0 range 11 .. 11;
LAST at 0 range 12 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
-------------------
-- OAR1_Register --
-------------------
subtype OAR1_ADD7_Field is HAL.UInt7;
subtype OAR1_ADD10_Field is HAL.UInt2;
-- Own address register 1
type OAR1_Register is record
-- Interface address
ADD0 : Boolean := False;
-- Interface address
ADD7 : OAR1_ADD7_Field := 16#0#;
-- Interface address
ADD10 : OAR1_ADD10_Field := 16#0#;
-- unspecified
Reserved_10_14 : HAL.UInt5 := 16#0#;
-- Addressing mode (slave mode)
ADDMODE : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OAR1_Register use record
ADD0 at 0 range 0 .. 0;
ADD7 at 0 range 1 .. 7;
ADD10 at 0 range 8 .. 9;
Reserved_10_14 at 0 range 10 .. 14;
ADDMODE at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-------------------
-- OAR2_Register --
-------------------
subtype OAR2_ADD2_Field is HAL.UInt7;
-- Own address register 2
type OAR2_Register is record
-- Dual addressing mode enable
ENDUAL : Boolean := False;
-- Interface address
ADD2 : OAR2_ADD2_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OAR2_Register use record
ENDUAL at 0 range 0 .. 0;
ADD2 at 0 range 1 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-----------------
-- DR_Register --
-----------------
subtype DR_DR_Field is HAL.Byte;
-- Data register
type DR_Register is record
-- 8-bit data register
DR : DR_DR_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR_Register use record
DR at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
------------------
-- SR1_Register --
------------------
-- Status register 1
type SR1_Register is record
-- Read-only. Start bit (Master mode)
SB : Boolean := False;
-- Read-only. Address sent (master mode)/matched (slave mode)
ADDR : Boolean := False;
-- Read-only. Byte transfer finished
BTF : Boolean := False;
-- Read-only. 10-bit header sent (Master mode)
ADD10 : Boolean := False;
-- Read-only. Stop detection (slave mode)
STOPF : Boolean := False;
-- unspecified
Reserved_5_5 : HAL.Bit := 16#0#;
-- Read-only. Data register not empty (receivers)
RxNE : Boolean := False;
-- Read-only. Data register empty (transmitters)
TxE : Boolean := False;
-- Bus error
BERR : Boolean := False;
-- Arbitration lost (master mode)
ARLO : Boolean := False;
-- Acknowledge failure
AF : Boolean := False;
-- Overrun/Underrun
OVR : Boolean := False;
-- PEC Error in reception
PECERR : Boolean := False;
-- unspecified
Reserved_13_13 : HAL.Bit := 16#0#;
-- Timeout or Tlow error
TIMEOUT : Boolean := False;
-- SMBus alert
SMBALERT : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR1_Register use record
SB at 0 range 0 .. 0;
ADDR at 0 range 1 .. 1;
BTF at 0 range 2 .. 2;
ADD10 at 0 range 3 .. 3;
STOPF at 0 range 4 .. 4;
Reserved_5_5 at 0 range 5 .. 5;
RxNE at 0 range 6 .. 6;
TxE at 0 range 7 .. 7;
BERR at 0 range 8 .. 8;
ARLO at 0 range 9 .. 9;
AF at 0 range 10 .. 10;
OVR at 0 range 11 .. 11;
PECERR at 0 range 12 .. 12;
Reserved_13_13 at 0 range 13 .. 13;
TIMEOUT at 0 range 14 .. 14;
SMBALERT at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- SR2_Register --
------------------
subtype SR2_PEC_Field is HAL.Byte;
-- Status register 2
type SR2_Register is record
-- Read-only. Master/slave
MSL : Boolean;
-- Read-only. Bus busy
BUSY : Boolean;
-- Read-only. Transmitter/receiver
TRA : Boolean;
-- unspecified
Reserved_3_3 : HAL.Bit;
-- Read-only. General call address (Slave mode)
GENCALL : Boolean;
-- Read-only. SMBus device default address (Slave mode)
SMBDEFAULT : Boolean;
-- Read-only. SMBus host header (Slave mode)
SMBHOST : Boolean;
-- Read-only. Dual flag (Slave mode)
DUALF : Boolean;
-- Read-only. acket error checking register
PEC : SR2_PEC_Field;
-- unspecified
Reserved_16_31 : HAL.Short;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR2_Register use record
MSL at 0 range 0 .. 0;
BUSY at 0 range 1 .. 1;
TRA at 0 range 2 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
GENCALL at 0 range 4 .. 4;
SMBDEFAULT at 0 range 5 .. 5;
SMBHOST at 0 range 6 .. 6;
DUALF at 0 range 7 .. 7;
PEC at 0 range 8 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- CCR_Register --
------------------
subtype CCR_CCR_Field is HAL.UInt12;
-- Clock control register
type CCR_Register is record
-- Clock control register in Fast/Standard mode (Master mode)
CCR : CCR_CCR_Field := 16#0#;
-- unspecified
Reserved_12_13 : HAL.UInt2 := 16#0#;
-- Fast mode duty cycle
DUTY : Boolean := False;
-- I2C master mode selection
F_S : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCR_Register use record
CCR at 0 range 0 .. 11;
Reserved_12_13 at 0 range 12 .. 13;
DUTY at 0 range 14 .. 14;
F_S at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
--------------------
-- TRISE_Register --
--------------------
subtype TRISE_TRISE_Field is HAL.UInt6;
-- TRISE register
type TRISE_Register is record
-- Maximum rise time in Fast/Standard mode (Master mode)
TRISE : TRISE_TRISE_Field := 16#2#;
-- unspecified
Reserved_6_31 : HAL.UInt26 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TRISE_Register use record
TRISE at 0 range 0 .. 5;
Reserved_6_31 at 0 range 6 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Inter-integrated circuit
type I2C_Peripheral is record
-- Control register 1
CR1 : CR1_Register;
-- Control register 2
CR2 : CR2_Register;
-- Own address register 1
OAR1 : OAR1_Register;
-- Own address register 2
OAR2 : OAR2_Register;
-- Data register
DR : DR_Register;
-- Status register 1
SR1 : SR1_Register;
-- Status register 2
SR2 : SR2_Register;
-- Clock control register
CCR : CCR_Register;
-- TRISE register
TRISE : TRISE_Register;
end record
with Volatile;
for I2C_Peripheral use record
CR1 at 0 range 0 .. 31;
CR2 at 4 range 0 .. 31;
OAR1 at 8 range 0 .. 31;
OAR2 at 12 range 0 .. 31;
DR at 16 range 0 .. 31;
SR1 at 20 range 0 .. 31;
SR2 at 24 range 0 .. 31;
CCR at 28 range 0 .. 31;
TRISE at 32 range 0 .. 31;
end record;
-- Inter-integrated circuit
I2C1_Periph : aliased I2C_Peripheral
with Import, Address => I2C1_Base;
-- Inter-integrated circuit
I2C2_Periph : aliased I2C_Peripheral
with Import, Address => I2C2_Base;
-- Inter-integrated circuit
I2C3_Periph : aliased I2C_Peripheral
with Import, Address => I2C3_Base;
end STM32_SVD.I2C;
|
-- This spec has been automatically generated from STM32F429x.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
with HAL;
with System;
package STM32_SVD.I2C is
pragma Preelaborate;
---------------
-- Registers --
---------------
------------------
-- CR1_Register --
------------------
-- Control register 1
type CR1_Register is record
-- Peripheral enable
PE : Boolean := False;
-- SMBus mode
SMBUS : Boolean := False;
-- unspecified
Reserved_2_2 : HAL.Bit := 16#0#;
-- SMBus type
SMBTYPE : Boolean := False;
-- ARP enable
ENARP : Boolean := False;
-- PEC enable
ENPEC : Boolean := False;
-- General call enable
ENGC : Boolean := False;
-- Clock stretching disable (Slave mode)
NOSTRETCH : Boolean := False;
-- Start generation
START : Boolean := False;
-- Stop generation
STOP : Boolean := False;
-- Acknowledge enable
ACK : Boolean := False;
-- Acknowledge/PEC Position (for data reception)
POS : Boolean := False;
-- Packet error checking
PEC : Boolean := False;
-- SMBus alert
ALERT : Boolean := False;
-- unspecified
Reserved_14_14 : HAL.Bit := 16#0#;
-- Software reset
SWRST : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR1_Register use record
PE at 0 range 0 .. 0;
SMBUS at 0 range 1 .. 1;
Reserved_2_2 at 0 range 2 .. 2;
SMBTYPE at 0 range 3 .. 3;
ENARP at 0 range 4 .. 4;
ENPEC at 0 range 5 .. 5;
ENGC at 0 range 6 .. 6;
NOSTRETCH at 0 range 7 .. 7;
START at 0 range 8 .. 8;
STOP at 0 range 9 .. 9;
ACK at 0 range 10 .. 10;
POS at 0 range 11 .. 11;
PEC at 0 range 12 .. 12;
ALERT at 0 range 13 .. 13;
Reserved_14_14 at 0 range 14 .. 14;
SWRST at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- CR2_Register --
------------------
subtype CR2_FREQ_Field is HAL.UInt6;
-- Control register 2
type CR2_Register is record
-- Peripheral clock frequency
FREQ : CR2_FREQ_Field := 16#0#;
-- unspecified
Reserved_6_7 : HAL.UInt2 := 16#0#;
-- Error interrupt enable
ITERREN : Boolean := False;
-- Event interrupt enable
ITEVTEN : Boolean := False;
-- Buffer interrupt enable
ITBUFEN : Boolean := False;
-- DMA requests enable
DMAEN : Boolean := False;
-- DMA last transfer
LAST : Boolean := False;
-- unspecified
Reserved_13_31 : HAL.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR2_Register use record
FREQ at 0 range 0 .. 5;
Reserved_6_7 at 0 range 6 .. 7;
ITERREN at 0 range 8 .. 8;
ITEVTEN at 0 range 9 .. 9;
ITBUFEN at 0 range 10 .. 10;
DMAEN at 0 range 11 .. 11;
LAST at 0 range 12 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
-------------------
-- OAR1_Register --
-------------------
subtype OAR1_ADD7_Field is HAL.UInt7;
subtype OAR1_ADD10_Field is HAL.UInt2;
-- Own address register 1
type OAR1_Register is record
-- Interface address
ADD0 : Boolean := False;
-- Interface address
ADD7 : OAR1_ADD7_Field := 16#0#;
-- Interface address
ADD10 : OAR1_ADD10_Field := 16#0#;
-- unspecified
Reserved_10_14 : HAL.UInt5 := 16#0#;
-- Addressing mode (slave mode)
ADDMODE : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OAR1_Register use record
ADD0 at 0 range 0 .. 0;
ADD7 at 0 range 1 .. 7;
ADD10 at 0 range 8 .. 9;
Reserved_10_14 at 0 range 10 .. 14;
ADDMODE at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-------------------
-- OAR2_Register --
-------------------
subtype OAR2_ADD2_Field is HAL.UInt7;
-- Own address register 2
type OAR2_Register is record
-- Dual addressing mode enable
ENDUAL : Boolean := False;
-- Interface address
ADD2 : OAR2_ADD2_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OAR2_Register use record
ENDUAL at 0 range 0 .. 0;
ADD2 at 0 range 1 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-----------------
-- DR_Register --
-----------------
subtype DR_DR_Field is HAL.Byte;
-- Data register
type DR_Register is record
-- 8-bit data register
DR : DR_DR_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR_Register use record
DR at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
------------------
-- SR1_Register --
------------------
-- Status register 1
type SR1_Register is record
-- Read-only. Start bit (Master mode)
SB : Boolean := False;
-- Read-only. Address sent (master mode)/matched (slave mode)
ADDR : Boolean := False;
-- Read-only. Byte transfer finished
BTF : Boolean := False;
-- Read-only. 10-bit header sent (Master mode)
ADD10 : Boolean := False;
-- Read-only. Stop detection (slave mode)
STOPF : Boolean := False;
-- unspecified
Reserved_5_5 : HAL.Bit := 16#0#;
-- Read-only. Data register not empty (receivers)
RxNE : Boolean := False;
-- Read-only. Data register empty (transmitters)
TxE : Boolean := False;
-- Bus error
BERR : Boolean := False;
-- Arbitration lost (master mode)
ARLO : Boolean := False;
-- Acknowledge failure
AF : Boolean := False;
-- Overrun/Underrun
OVR : Boolean := False;
-- PEC Error in reception
PECERR : Boolean := False;
-- unspecified
Reserved_13_13 : HAL.Bit := 16#0#;
-- Timeout or Tlow error
TIMEOUT : Boolean := False;
-- SMBus alert
SMBALERT : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR1_Register use record
SB at 0 range 0 .. 0;
ADDR at 0 range 1 .. 1;
BTF at 0 range 2 .. 2;
ADD10 at 0 range 3 .. 3;
STOPF at 0 range 4 .. 4;
Reserved_5_5 at 0 range 5 .. 5;
RxNE at 0 range 6 .. 6;
TxE at 0 range 7 .. 7;
BERR at 0 range 8 .. 8;
ARLO at 0 range 9 .. 9;
AF at 0 range 10 .. 10;
OVR at 0 range 11 .. 11;
PECERR at 0 range 12 .. 12;
Reserved_13_13 at 0 range 13 .. 13;
TIMEOUT at 0 range 14 .. 14;
SMBALERT at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- SR2_Register --
------------------
subtype SR2_PEC_Field is HAL.Byte;
-- Status register 2
type SR2_Register is record
-- Read-only. Master/slave
MSL : Boolean;
-- Read-only. Bus busy
BUSY : Boolean;
-- Read-only. Transmitter/receiver
TRA : Boolean;
-- unspecified
Reserved_3_3 : HAL.Bit;
-- Read-only. General call address (Slave mode)
GENCALL : Boolean;
-- Read-only. SMBus device default address (Slave mode)
SMBDEFAULT : Boolean;
-- Read-only. SMBus host header (Slave mode)
SMBHOST : Boolean;
-- Read-only. Dual flag (Slave mode)
DUALF : Boolean;
-- Read-only. acket error checking register
PEC : SR2_PEC_Field;
-- unspecified
Reserved_16_31 : HAL.Short;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR2_Register use record
MSL at 0 range 0 .. 0;
BUSY at 0 range 1 .. 1;
TRA at 0 range 2 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
GENCALL at 0 range 4 .. 4;
SMBDEFAULT at 0 range 5 .. 5;
SMBHOST at 0 range 6 .. 6;
DUALF at 0 range 7 .. 7;
PEC at 0 range 8 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
------------------
-- CCR_Register --
------------------
subtype CCR_CCR_Field is HAL.UInt12;
-- Clock control register
type CCR_Register is record
-- Clock control register in Fast/Standard mode (Master mode)
CCR : CCR_CCR_Field := 16#0#;
-- unspecified
Reserved_12_13 : HAL.UInt2 := 16#0#;
-- Fast mode duty cycle
DUTY : Boolean := False;
-- I2C master mode selection
F_S : Boolean := False;
-- unspecified
Reserved_16_31 : HAL.Short := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCR_Register use record
CCR at 0 range 0 .. 11;
Reserved_12_13 at 0 range 12 .. 13;
DUTY at 0 range 14 .. 14;
F_S at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
--------------------
-- TRISE_Register --
--------------------
subtype TRISE_TRISE_Field is HAL.UInt6;
-- TRISE register
type TRISE_Register is record
-- Maximum rise time in Fast/Standard mode (Master mode)
TRISE : TRISE_TRISE_Field := 16#2#;
-- unspecified
Reserved_6_31 : HAL.UInt26 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TRISE_Register use record
TRISE at 0 range 0 .. 5;
Reserved_6_31 at 0 range 6 .. 31;
end record;
-------------------
-- FLTR_Register --
-------------------
subtype FLTR_DNF_Field is HAL.UInt4;
-- FLTR register
type FLTR_Register is record
-- Digital Noise Filter. 0 to disable, or filtering capability up to N *
-- TPCLK1
DNF : FLTR_DNF_Field := 16#0#;
-- Analog noise filter OFF
ANOFF : Boolean := False;
-- unspecified
Reserved_5_31 : HAL.UInt27 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for FLTR_Register use record
DNF at 0 range 0 .. 3;
ANOFF at 0 range 4 .. 4;
Reserved_5_31 at 0 range 5 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Inter-integrated circuit
type I2C_Peripheral is record
-- Control register 1
CR1 : CR1_Register;
-- Control register 2
CR2 : CR2_Register;
-- Own address register 1
OAR1 : OAR1_Register;
-- Own address register 2
OAR2 : OAR2_Register;
-- Data register
DR : DR_Register;
-- Status register 1
SR1 : SR1_Register;
-- Status register 2
SR2 : SR2_Register;
-- Clock control register
CCR : CCR_Register;
-- TRISE register
TRISE : TRISE_Register;
-- FLTR register
FLTR : FLTR_Register;
end record
with Volatile;
for I2C_Peripheral use record
CR1 at 0 range 0 .. 31;
CR2 at 4 range 0 .. 31;
OAR1 at 8 range 0 .. 31;
OAR2 at 12 range 0 .. 31;
DR at 16 range 0 .. 31;
SR1 at 20 range 0 .. 31;
SR2 at 24 range 0 .. 31;
CCR at 28 range 0 .. 31;
TRISE at 32 range 0 .. 31;
FLTR at 36 range 0 .. 31;
end record;
-- Inter-integrated circuit
I2C1_Periph : aliased I2C_Peripheral
with Import, Address => I2C1_Base;
-- Inter-integrated circuit
I2C2_Periph : aliased I2C_Peripheral
with Import, Address => I2C2_Base;
-- Inter-integrated circuit
I2C3_Periph : aliased I2C_Peripheral
with Import, Address => I2C3_Base;
end STM32_SVD.I2C;
|
Add missing field in the I2C peripheral for the STM32F42x.
|
Add missing field in the I2C peripheral for the STM32F42x.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
5e0a2ab3ca7c915925ae4c68d7eaacf90a50cd30
|
src/orka/implementation/orka-transforms-simd_quaternions.adb
|
src/orka/implementation/orka-transforms-simd_quaternions.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
package body Orka.Transforms.SIMD_Quaternions is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type);
function Vector_Part (Elements : Quaternion) return Vector4 is
begin
return Result : Vector4 := Vector4 (Elements) do
Result (W) := 0.0;
end return;
end Vector_Part;
function "*" (Left, Right : Quaternion) return Quaternion is
use Vectors;
Lv : constant Vector4 := Vector_Part (Left);
Rv : constant Vector4 := Vector_Part (Right);
Ls : constant Vectors.Element_Type := Left (W);
Rs : constant Vectors.Element_Type := Right (W);
V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv);
S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv);
begin
return Result : Quaternion := Quaternion (V) do
Result (W) := S;
end return;
end "*";
function Conjugate (Elements : Quaternion) return Quaternion is
Element_W : constant Vectors.Element_Type := Elements (W);
use Vectors;
begin
return Result : Quaternion := Quaternion (-Vector4 (Elements)) do
Result (W) := Element_W;
end return;
end Conjugate;
function Norm (Elements : Quaternion) return Vectors.Element_Type is
(Vectors.Magnitude (Vector4 (Elements)));
function Normalize (Elements : Quaternion) return Quaternion is
(Quaternion (Vectors.Normalize (Vector4 (Elements))));
function Normalized (Elements : Quaternion) return Boolean is
(Vectors.Normalized (Vector4 (Elements)));
function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is
use type Vectors.Element_Type;
Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0;
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
Axis : Vector4 := Vector4 (Elements) * (1.0 / SA);
begin
Axis (W) := 0.0;
return (Axis => Axis, Angle => Angle);
end To_Axis_Angle;
function R
(Axis : Vector4;
Angle : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0);
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
begin
return Result : Quaternion := Quaternion (Axis * SA) do
Result (W) := CA;
end return;
end R;
function R (Left, Right : Vector4) return Quaternion is
use type Vectors.Element_Type;
S : constant Vector4 := Vectors.Normalize (Left);
T : constant Vector4 := Vectors.Normalize (Right);
E : constant Vectors.Element_Type := Vectors.Dot (S, T);
SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E));
use Vectors;
begin
-- Division by zero if Left and Right are in opposite direction.
-- Use rotation axis perpendicular to s and angle of 180 degrees
if SRE /= 0.0 then
-- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering
-- (third edition, 2008)
declare
Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T));
begin
Result (W) := SRE / 2.0;
return Normalize (Result);
end;
else
if abs S (Z) < abs S (X) then
return R ((S (Y), -S (X), 0.0, 0.0), 180.0);
else
return R ((0.0, -S (Z), S (Y), 0.0), 180.0);
end if;
end if;
end R;
function Difference (Left, Right : Quaternion) return Quaternion is
begin
return Right * Conjugate (Left);
end Difference;
procedure Rotate_At_Origin
(Vector : in out Vector4;
Elements : Quaternion)
is
Result : Vectors.Vector_Type;
begin
Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements));
Vector := Result;
end Rotate_At_Origin;
function Lerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
use Vectors;
begin
return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right)));
end Lerp;
function Slerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right));
Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle);
SA : constant Vectors.Element_Type := EF.Sin (Angle);
SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle);
SR : constant Vectors.Element_Type := EF.Sin (Time * Angle);
use Vectors;
begin
return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right));
end Slerp;
function Image (Elements : Quaternion) return String is
(Vectors.Image (Vectors.Vector_Type (Elements)));
end Orka.Transforms.SIMD_Quaternions;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
package body Orka.Transforms.SIMD_Quaternions is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type);
function Vector_Part (Elements : Quaternion) return Vector4 is
begin
return Result : Vector4 := Vector4 (Elements) do
Result (W) := 0.0;
end return;
end Vector_Part;
function "*" (Left, Right : Quaternion) return Quaternion is
use Vectors;
Lv : constant Vector4 := Vector_Part (Left);
Rv : constant Vector4 := Vector_Part (Right);
Ls : constant Vectors.Element_Type := Left (W);
Rs : constant Vectors.Element_Type := Right (W);
V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv);
S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv);
begin
return Result : Quaternion := Quaternion (V) do
Result (W) := S;
end return;
end "*";
function Conjugate (Elements : Quaternion) return Quaternion is
Element_W : constant Vectors.Element_Type := Elements (W);
use Vectors;
begin
return Result : Quaternion := Quaternion (-Vector4 (Elements)) do
Result (W) := Element_W;
end return;
end Conjugate;
function Norm (Elements : Quaternion) return Vectors.Element_Type is
(Vectors.Magnitude (Vector4 (Elements)));
function Normalize (Elements : Quaternion) return Quaternion is
(Quaternion (Vectors.Normalize (Vector4 (Elements))));
function Normalized (Elements : Quaternion) return Boolean is
(Vectors.Normalized (Vector4 (Elements)));
function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is
use type Vectors.Element_Type;
Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0;
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
Axis : Vector4 := Vector4 (Elements) * (1.0 / SA);
begin
Axis (W) := 0.0;
return (Axis => Axis, Angle => Angle);
end To_Axis_Angle;
function R
(Axis : Vector4;
Angle : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0);
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
begin
return Result : Quaternion := Quaternion (Axis * SA) do
Result (W) := CA;
end return;
end R;
function R (Left, Right : Vector4) return Quaternion is
use type Vectors.Element_Type;
S : constant Vector4 := Vectors.Normalize (Left);
T : constant Vector4 := Vectors.Normalize (Right);
E : constant Vectors.Element_Type := Vectors.Dot (S, T);
SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E));
use Vectors;
begin
-- Division by zero if Left and Right are in opposite direction.
-- Use rotation axis perpendicular to s and angle of 180 degrees
if SRE /= 0.0 then
-- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering
-- (third edition, 2008)
declare
Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T));
begin
Result (W) := SRE / 2.0;
return Normalize (Result);
end;
else
if abs S (Z) < abs S (X) then
return R ((S (Y), -S (X), 0.0, 0.0), Ada.Numerics.Pi);
else
return R ((0.0, -S (Z), S (Y), 0.0), Ada.Numerics.Pi);
end if;
end if;
end R;
function Difference (Left, Right : Quaternion) return Quaternion is
begin
return Right * Conjugate (Left);
end Difference;
procedure Rotate_At_Origin
(Vector : in out Vector4;
Elements : Quaternion)
is
Result : Vectors.Vector_Type;
begin
Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements));
Vector := Result;
end Rotate_At_Origin;
function Lerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
use Vectors;
begin
return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right)));
end Lerp;
function Slerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right));
Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle);
SA : constant Vectors.Element_Type := EF.Sin (Angle);
SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle);
SR : constant Vectors.Element_Type := EF.Sin (Time * Angle);
use Vectors;
begin
return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right));
end Slerp;
function Image (Elements : Quaternion) return String is
(Vectors.Image (Vectors.Vector_Type (Elements)));
end Orka.Transforms.SIMD_Quaternions;
|
Fix function R in SIMD_Quaternions to use Pi instead of 180.0
|
orka: Fix function R in SIMD_Quaternions to use Pi instead of 180.0
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
22cdaa7b60421ba77fea76b24b5a10873b4be9e0
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup to start the application.
procedure Start (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and wait for the application to be started.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
Declare the Start action procedure
|
Declare the Start action procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0c933458f45bb8d3aa89eee64938eb3081704db9
|
ibv_message_passing_ada_project/source/get_rdate/get_rdate.adb
|
ibv_message_passing_ada_project/source/get_rdate/get_rdate.adb
|
-- @file get_rdate.adb
-- @date 7 July 2019
-- @author Chester Gillon
-- @brief Example program using GNAT.sockets to get the date from a RFC 868 TCP protocol server
-- @details The output as seconds since the Linux epoch can be verified by running:
-- $ date -d @`./get_rdate sandy-ubuntu`
-- Sun 7 Jul 19:42:14 BST 2019
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Unchecked_Conversion;
with Interfaces;
with System;
with GNAT.Sockets;
procedure Get_RDate is
Rdate_Client : GNAT.Sockets.Socket_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
Channel : GNAT.Sockets.Stream_Access;
Rdate_Port : GNAT.Sockets.Port_Type := 37;
-- Define a big-endian (network order) structure to receive the rdate time as a 32-bit number of seconds
-- since the epoch of 00:00 (midnight) 1 January 1900 GMT
type Rdate_Time is record
Time : Interfaces.Unsigned_32;
end record;
for Rdate_Time use record
Time at 0 range 0 .. 31;
end record;
type Rdate_Time_Packet is new Rdate_Time;
for Rdate_Time_Packet'Bit_Order use System.High_Order_First;
for Rdate_Time_Packet'Scalar_Storage_Order use System.High_Order_First;
function From_Rdate_Packet is new Ada.Unchecked_Conversion (Rdate_Time_Packet, Rdate_Time);
Raw_Time : Rdate_Time_Packet;
Host_Rdate_Time : Rdate_Time;
-- From RFC 868
Rdate_To_Linux_Epoch_Seconds : constant := 2208988800;
Time_Since_Linux_Epoch : Interfaces.Unsigned_32;
begin
if Ada.Command_Line.Argument_Count /= 1 then
Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & "get_rdate <rdate_server>");
return;
end if;
declare
Rdate_Server : constant String := Ada.Command_Line.Argument (1);
begin
-- Connect to the specified rdate server and retrieve a packet with the time
GNAT.Sockets.Initialize;
GNAT.Sockets.Create_Socket (Rdate_Client);
Address.Addr := GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (Rdate_Server));
Address.Port := Rdate_Port;
GNAT.Sockets.Connect_Socket (Rdate_Client, Address);
Channel := GNAT.Sockets.Stream (Rdate_Client);
Rdate_Time_Packet'Read (Channel, Raw_Time);
GNAT.Sockets.Close_Socket (Rdate_Client);
-- Display the time as the number of seconds since the Linux epoch.
Host_Rdate_Time := From_Rdate_Packet (Raw_Time);
Time_Since_Linux_Epoch := Interfaces."-" (Host_Rdate_Time.Time, Rdate_To_Linux_Epoch_Seconds);
declare
Raw_Image : constant String := Interfaces.Unsigned_32'Image (Time_Since_Linux_Epoch);
begin
Ada.Text_Io.Put (Ada.Strings.Fixed.Trim (Raw_Image, Ada.Strings.Left));
end;
end;
end Get_Rdate;
|
-- @file get_rdate.adb
-- @date 7 July 2019
-- @author Chester Gillon
-- @brief Example program using GNAT.sockets to get the date from a RFC 868 TCP protocol server
-- @details The output as seconds since the Linux epoch can be verified by running:
-- $ date -d @`./get_rdate sandy-ubuntu`
-- Sun 7 Jul 19:42:14 BST 2019
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Interfaces; use Interfaces;
with GNAT.Sockets;
procedure Get_RDate is
Rdate_Client : GNAT.Sockets.Socket_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
Channel : GNAT.Sockets.Stream_Access;
Rdate_Port : GNAT.Sockets.Port_Type := 37;
-- Define am array to receive the rdate time as a big-endian 32-bit number of seconds
-- since the epoch of 00:00 (midnight) 1 January 1900 GMT
type Rdate_Time_Packet is Array (0..3) of Interfaces.Unsigned_8;
Raw_Time : Rdate_Time_Packet;
Host_Rdate_Time : Interfaces.Unsigned_32;
-- From RFC 868
Rdate_To_Linux_Epoch_Seconds : constant := 2208988800;
Time_Since_Linux_Epoch : Interfaces.Unsigned_32;
begin
if Ada.Command_Line.Argument_Count /= 1 then
Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & "get_rdate <rdate_server>");
return;
end if;
declare
Rdate_Server : constant String := Ada.Command_Line.Argument (1);
begin
-- Connect to the specified rdate server and retrieve a packet with the time
GNAT.Sockets.Initialize;
GNAT.Sockets.Create_Socket (Rdate_Client);
Address.Addr := GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (Rdate_Server));
Address.Port := Rdate_Port;
GNAT.Sockets.Connect_Socket (Rdate_Client, Address);
Channel := GNAT.Sockets.Stream (Rdate_Client);
Rdate_Time_Packet'Read (Channel, Raw_Time);
GNAT.Sockets.Close_Socket (Rdate_Client);
-- Convert the big-endian received rdate
Host_Rdate_Time := Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(0)), 24) +
Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(1)), 16) +
Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(2)), 8) +
Interfaces.Unsigned_32 (Raw_Time(3));
-- Display the time as the number of seconds since the Linux epoch.
Time_Since_Linux_Epoch := Host_Rdate_Time - Rdate_To_Linux_Epoch_Seconds;
declare
Raw_Image : constant String := Interfaces.Unsigned_32'Image (Time_Since_Linux_Epoch);
begin
Ada.Text_Io.Put (Ada.Strings.Fixed.Trim (Raw_Image, Ada.Strings.Left));
end;
end;
end Get_Rdate;
|
Change get_rdate to manually convert the big-endian rdate, rather than a record using 'Scalar_Storage_Order, to simplify the code.
|
Change get_rdate to manually convert the big-endian rdate, rather than a record using 'Scalar_Storage_Order, to simplify the code.
|
Ada
|
mit
|
Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing
|
34910bf32f14d3e4aa1b75126b7711fbc91f6784
|
src/wiki-attributes.ads
|
src/wiki-attributes.ads
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
private with Ada.Containers.Vectors;
private with Ada.Finalization;
-- == Attributes ==
-- The <tt>Attributes</tt> package defines a simple management of attributes for
-- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt>
-- with some operations to append or query for an attribute.
package Wiki.Attributes is
pragma Preelaborate;
type Cursor is private;
-- Get the attribute name.
function Get_Name (Position : in Cursor) return String;
-- Get the attribute value.
function Get_Value (Position : in Cursor) return String;
-- Get the attribute wide value.
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String;
-- Returns True if the cursor has a valid attribute.
function Has_Element (Position : in Cursor) return Boolean;
-- Move the cursor to the next attribute.
procedure Next (Position : in out Cursor);
-- A list of attributes.
type Attribute_List_Type is limited private;
-- Find the attribute with the given name.
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor;
-- 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);
-- 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);
-- Get the cursor to get access to the first attribute.
function First (List : in Attribute_List_Type) return Cursor;
-- Get the number of attributes in the list.
function Length (List : in Attribute_List_Type) return Natural;
-- Clear the list and remove all existing attributes.
procedure Clear (List : in out Attribute_List_Type);
private
type Attribute (Name_Length, Value_Length : Natural) is limited record
Name : String (1 .. Name_Length);
Value : Wide_Wide_String (1 .. Value_Length);
end record;
type Attribute_Access is access all Attribute;
package Attribute_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Attribute_Access);
subtype Attribute_Vector is Attribute_Vectors.Vector;
type Cursor is record
Pos : Attribute_Vectors.Cursor;
end record;
type Attribute_List_Type is limited new Ada.Finalization.Limited_Controlled with record
List : Attribute_Vector;
end record;
-- Finalize the attribute list releasing any storage.
overriding
procedure Finalize (List : in out Attribute_List_Type);
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.Strings.Wide_Wide_Unbounded;
private with Ada.Containers.Vectors;
private with Ada.Finalization;
-- == Attributes ==
-- The <tt>Attributes</tt> package defines a simple management of attributes for
-- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt>
-- with some operations to append or query for an attribute.
package Wiki.Attributes is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Cursor is private;
-- Get the attribute name.
function Get_Name (Position : in Cursor) return String;
-- Get the attribute value.
function Get_Value (Position : in Cursor) return String;
-- Get the attribute wide value.
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String;
-- Get the attribute wide value.
function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String;
-- Returns True if the cursor has a valid attribute.
function Has_Element (Position : in Cursor) return Boolean;
-- Move the cursor to the next attribute.
procedure Next (Position : in out Cursor);
-- A list of attributes.
type Attribute_List_Type is limited private;
-- Find the attribute with the given name.
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor;
-- 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;
-- 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);
-- 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);
-- Get the cursor to get access to the first attribute.
function First (List : in Attribute_List_Type) return Cursor;
-- Get the number of attributes in the list.
function Length (List : in Attribute_List_Type) return Natural;
-- Clear the list and remove all existing attributes.
procedure Clear (List : in out Attribute_List_Type);
private
type Attribute (Name_Length, Value_Length : Natural) is limited record
Name : String (1 .. Name_Length);
Value : Wide_Wide_String (1 .. Value_Length);
end record;
type Attribute_Access is access all Attribute;
package Attribute_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Attribute_Access);
subtype Attribute_Vector is Attribute_Vectors.Vector;
type Cursor is record
Pos : Attribute_Vectors.Cursor;
end record;
type Attribute_List_Type is limited new Ada.Finalization.Limited_Controlled with record
List : Attribute_Vector;
end record;
-- Finalize the attribute list releasing any storage.
overriding
procedure Finalize (List : in out Attribute_List_Type);
end Wiki.Attributes;
|
Declare Get_Unbounded_Wide_Value and Get_Attribute functions
|
Declare Get_Unbounded_Wide_Value and Get_Attribute functions
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
70a9b3a6ece3135329384786b91a98a485f76ad4
|
src/ado-utils.adb
|
src/ado-utils.adb
|
-----------------------------------------------------------------------
-- ado-utils -- Utility operations for ADO
-- 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.
-----------------------------------------------------------------------
package body ADO.Utils is
-- ------------------------------
-- Build a bean object from the identifier.
-- ------------------------------
function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is
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 To_Object;
-- ------------------------------
-- Build the identifier from the bean object.
-- ------------------------------
function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is
begin
if Util.Beans.Objects.Is_Null (Value) then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value));
end if;
end To_Identifier;
-- ------------------------------
-- Compute the hash of the identifier.
-- ------------------------------
function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is
use Ada.Containers;
begin
if Key < 0 then
return Hash_Type (-Key);
else
return Hash_Type (Key);
end if;
end Hash;
-- ------------------------------
-- Return the identifier list as a comma separated list of identifiers.
-- ------------------------------
function To_Parameter_List (List : in Identifier_Vector) return String is
use Identifier_Vectors;
Result : Ada.Strings.Unbounded.Unbounded_String;
Pos : Identifier_Cursor := List.First;
Need_Comma : Boolean := False;
begin
while Identifier_Vectors.Has_Element (Pos) loop
if Need_Comma then
Ada.Strings.Unbounded.Append (Result, ",");
end if;
Ada.Strings.Unbounded.Append (Result, ADO.Identifier'Image (Element (Pos)));
Need_Comma := True;
Next (Pos);
end loop;
return Ada.Strings.Unbounded.To_String (Result);
end To_Parameter_List;
end ADO.Utils;
|
-----------------------------------------------------------------------
-- ado-utils -- Utility operations for ADO
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Utils is
-- ------------------------------
-- Build a bean object from the identifier.
-- ------------------------------
function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is
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 To_Object;
-- ------------------------------
-- Build the identifier from the bean object.
-- ------------------------------
function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is
begin
if Util.Beans.Objects.Is_Null (Value) then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value));
end if;
end To_Identifier;
-- ------------------------------
-- Compute the hash of the identifier.
-- ------------------------------
function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is
use Ada.Containers;
begin
if Key < 0 then
return Hash_Type (-Key);
else
return Hash_Type (Key);
end if;
end Hash;
-- ------------------------------
-- Return the identifier list as a comma separated list of identifiers.
-- ------------------------------
function To_Parameter_List (List : in Identifier_Vector) return String is
use Identifier_Vectors;
Result : Ada.Strings.Unbounded.Unbounded_String;
Pos : Identifier_Cursor := List.First;
Need_Comma : Boolean := False;
begin
while Identifier_Vectors.Has_Element (Pos) loop
if Need_Comma then
Ada.Strings.Unbounded.Append (Result, ",");
end if;
Ada.Strings.Unbounded.Append (Result, ADO.Identifier'Image (Element (Pos)));
Need_Comma := True;
Next (Pos);
end loop;
return Ada.Strings.Unbounded.To_String (Result);
end To_Parameter_List;
-- ------------------------------
-- Write the entity to the serialization stream (JSON/XML).
-- ------------------------------
procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Value : in ADO.Identifier) is
begin
Stream.Write_Long_Entity (Name, Long_Long_Integer (Value));
end Write_Entity;
end ADO.Utils;
|
Implement the Write_Entity operation
|
Implement the Write_Entity operation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
5842bde2b57c219217d85454d05a4b34601538f9
|
src/asf-events-actions.ads
|
src/asf-events-actions.ads
|
-----------------------------------------------------------------------
-- asf-events-actions -- Actions Events
-- 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 EL.Expressions;
with EL.Beans.Methods.Proc_1;
with ASF.Contexts.Faces;
with ASF.Components.Base;
package ASF.Events.Actions is
package Action_Method is
new EL.Beans.Methods.Proc_1 (Param1_Type => Ada.Strings.Unbounded.Unbounded_String);
-- ------------------------------
-- Action event
-- ------------------------------
-- The <b>Action_Event</b> is posted when a method bean action must be executed
-- as a result of a command (such as button press). The method action must return
-- an outcome string that indicates which view to return.
type Action_Event is new Faces_Event with private;
type Action_Event_Access is access all Action_Event'Class;
-- Get the method expression to invoke
function Get_Method (Event : in Action_Event) return EL.Expressions.Method_Expression;
-- Post an <b>Action_Event</b> on the component.
procedure Post_Event (UI : in out Components.Base.UIComponent'Class;
Method : in EL.Expressions.Method_Expression);
-- ------------------------------
-- Action Listener
-- ------------------------------
-- The <b>Action_Listener</b> is the interface to receive the <b>Action_Event</b>.
type Action_Listener is limited interface and Util.Events.Event_Listener;
type Action_Listener_Access is access all Action_Listener'Class;
-- Process the action associated with the action event.
procedure Process_Action (Listener : in Action_Listener;
Event : in Action_Event'Class;
Context : in out Contexts.Faces.Faces_Context'Class) is abstract;
private
type Action_Event is new Faces_Event with record
Method : EL.Expressions.Method_Expression;
end record;
end ASF.Events.Actions;
|
-----------------------------------------------------------------------
-- asf-events-actions -- Actions Events
-- 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 EL.Expressions;
with EL.Methods.Proc_1;
with ASF.Contexts.Faces;
with ASF.Components.Base;
package ASF.Events.Actions is
package Action_Method is
new EL.Methods.Proc_1 (Param1_Type => Ada.Strings.Unbounded.Unbounded_String);
-- ------------------------------
-- Action event
-- ------------------------------
-- The <b>Action_Event</b> is posted when a method bean action must be executed
-- as a result of a command (such as button press). The method action must return
-- an outcome string that indicates which view to return.
type Action_Event is new Faces_Event with private;
type Action_Event_Access is access all Action_Event'Class;
-- Get the method expression to invoke
function Get_Method (Event : in Action_Event) return EL.Expressions.Method_Expression;
-- Post an <b>Action_Event</b> on the component.
procedure Post_Event (UI : in out Components.Base.UIComponent'Class;
Method : in EL.Expressions.Method_Expression);
-- ------------------------------
-- Action Listener
-- ------------------------------
-- The <b>Action_Listener</b> is the interface to receive the <b>Action_Event</b>.
type Action_Listener is limited interface and Util.Events.Event_Listener;
type Action_Listener_Access is access all Action_Listener'Class;
-- Process the action associated with the action event.
procedure Process_Action (Listener : in Action_Listener;
Event : in Action_Event'Class;
Context : in out Contexts.Faces.Faces_Context'Class) is abstract;
private
type Action_Event is new Faces_Event with record
Method : EL.Expressions.Method_Expression;
end record;
end ASF.Events.Actions;
|
Fix compilation after refactoring of Ada-El and Ada-Util
|
Fix compilation after refactoring of Ada-El and Ada-Util
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0f63649460062bd6838ba677d70f599a1b53c52e
|
src/asf-views-facelets.adb
|
src/asf-views-facelets.adb
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015, 2017, 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.Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ASF.Views.Nodes.Reader;
with Input_Sources.File;
with Sax.Readers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
package body ASF.Views.Facelets is
use ASF.Views.Nodes;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets");
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info,
Name => ASF.Views.File_Info_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Facelet_Type,
Name => Facelet_Access);
-- Find in the factory for the facelet with the given name.
procedure Find (Factory : in out Facelet_Factory;
Name : in String;
Result : out Facelet);
-- Load the facelet node tree by reading the facelet XHTML file.
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Update the factory to store the facelet node tree
procedure Update (Factory : in out Facelet_Factory;
Facelet : in Facelet_Access);
-- ------------------------------
-- Returns True if the facelet is null/empty.
-- ------------------------------
function Is_Null (F : Facelet) return Boolean is
begin
return F.Facelet = null;
end Is_Null;
-- ------------------------------
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
-- ------------------------------
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
begin
Log.Debug ("Find facelet {0}", Name);
Find (Factory, Name, Result);
if Result.Facelet = null then
Load (Factory, Name, Context, Result);
if Result.Facelet = null then
return;
end if;
Update (Factory, Result.Facelet);
end if;
end Find_Facelet;
-- ------------------------------
-- Create the component tree from the facelet view.
-- ------------------------------
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access) is
Old : Unbounded_String;
begin
if View.Facelet /= null then
Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.Facelet.File.all),
Previous => Old);
View.Facelet.Root.Build_Children (Parent => Root, Context => Context);
Context.Set_Relative_Path (Path => Old);
end if;
end Build_View;
-- ------------------------------
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
-- ------------------------------
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean) is
begin
Log.Info ("Set facelet search directory to: '{0}'", Paths);
Factory.Factory := Components;
Factory.Paths := To_Unbounded_String (Paths);
Factory.Ignore_White_Spaces := Ignore_White_Spaces;
Factory.Ignore_Empty_Lines := Ignore_Empty_Lines;
Factory.Escape_Unknown_Tags := Escape_Unknown_Tags;
end Initialize;
-- ------------------------------
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
-- ------------------------------
function Find_Facelet_Path (Factory : Facelet_Factory;
Name : String) return String is
begin
return Util.Files.Find_File_Path (Name, To_String (Factory.Paths));
end Find_Facelet_Path;
-- ------------------------------
-- Find in the factory for the facelet with the given name.
-- ------------------------------
procedure Find (Factory : in out Facelet_Factory;
Name : in String;
Result : out Facelet) is
use Ada.Directories;
use Ada.Calendar;
begin
Result.Facelet := Factory.Map.Find (Name);
if Result.Facelet /= null then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Result.Facelet.Check_Time < Now then
if Modification_Time (Result.Facelet.File.Path) > Result.Facelet.Modify_Time then
Result.Facelet := null;
Log.Info ("Ignoring cache because file '{0}' was modified",
Result.Facelet.File.Path);
else
Result.Facelet.Check_Time := Now + CHECK_FILE_DELAY;
end if;
end if;
end;
end if;
end Find;
-- ------------------------------
-- Load the facelet node tree by reading the facelet XHTML file.
-- ------------------------------
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Path : constant String := Find_Facelet_Path (Factory, Name);
begin
if Path = "" or else not Ada.Directories.Exists (Path) then
Log.Warn ("Cannot read '{0}': file does not exist", Path);
Result.Facelet := null;
return;
end if;
declare
use type Ada.Calendar.Time;
Pos : constant Integer := Path'Last - Name'Length + 1;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock + CHECK_FILE_DELAY;
File : File_Info_Access;
Reader : ASF.Views.Nodes.Reader.Xhtml_Reader;
Read : Input_Sources.File.File_Input;
Mtime : Ada.Calendar.Time;
Ctx : aliased EL.Contexts.Default.Default_Context;
Root : ASF.Views.Nodes.Tag_Node_Access;
begin
if Pos <= Path'First then
File := Create_File_Info (Path, Path'First);
else
File := Create_File_Info (Path, Pos);
end if;
Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name,
Natural'Image (File.Relative_Pos));
Ctx.Set_Function_Mapper (Context.Get_Function_Mapper);
Mtime := Ada.Directories.Modification_Time (Path);
Input_Sources.File.Open (Path, Read);
-- If True, xmlns:* attributes will be reported in Start_Element
Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False);
Reader.Set_Feature (Sax.Readers.Validation_Feature, False);
Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces);
Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags);
Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines);
begin
Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access);
exception
when ASF.Views.Nodes.Reader.Parsing_Error =>
Free (File);
when E : others =>
Free (File);
Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path,
Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E));
end;
Root := Reader.Get_Root;
if File = null then
if Root /= null then
Root.Delete;
end if;
Result.Facelet := null;
else
Result.Facelet := new Facelet_Type '(Util.Refs.Ref_Entity with
Len => Name'Length,
Root => Root,
File => File,
Modify_Time => Mtime,
Check_Time => Now,
Name => Name);
end if;
Input_Sources.File.Close (Read);
end;
end Load;
-- ------------------------------
-- Update the factory to store the facelet node tree
-- ------------------------------
procedure Update (Factory : in out Facelet_Factory;
Facelet : in Facelet_Access) is
begin
Factory.Map.Insert (Facelet);
end Update;
-- ------------------------------
-- Clear the facelet cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Facelet_Factory) is
begin
Log.Info ("Clearing facelet cache");
Factory.Map.Clear;
end Clear_Cache;
protected body Facelet_Cache is
-- ------------------------------
-- Find the facelet entry associated with the given name.
-- ------------------------------
function Find (Name : in String) return Facelet_Access is
Key : aliased Facelet_Type := Facelet_Type '(Util.Refs.Ref_Entity with
Len => Name'Length,
Name => Name,
others => <>);
Pos : constant Facelet_Sets.Cursor := Map.Find (Key'Unchecked_Access);
begin
if Facelet_Sets.Has_Element (Pos) then
return Element (Pos);
else
return null;
end if;
end Find;
-- ------------------------------
-- Insert or replace the facelet entry associated with the given name.
-- ------------------------------
procedure Insert (Facelet : in Facelet_Access) is
begin
Map.Include (Facelet);
end Insert;
-- ------------------------------
-- Clear the cache.
-- ------------------------------
procedure Clear is
begin
loop
declare
Pos : Facelet_Sets.Cursor := Map.First;
Node : Facelet_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Map.Delete (Pos);
Free (Node.File);
ASF.Views.Nodes.Destroy (Node.Root);
Free (Node);
end;
end loop;
end Clear;
end Facelet_Cache;
-- ------------------------------
-- Free the storage held by the factory cache.
-- ------------------------------
overriding
procedure Finalize (Factory : in out Facelet_Factory) is
begin
Factory.Clear_Cache;
end Finalize;
end ASF.Views.Facelets;
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015, 2017, 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.Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ASF.Views.Nodes.Reader;
with Input_Sources.File;
with Sax.Readers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
package body ASF.Views.Facelets is
use ASF.Views.Nodes;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets");
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info,
Name => ASF.Views.File_Info_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Facelet_Type,
Name => Facelet_Access);
-- Find in the factory for the facelet with the given name.
procedure Find (Factory : in out Facelet_Factory;
Name : in String;
Result : out Facelet);
-- Load the facelet node tree by reading the facelet XHTML file.
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Update the factory to store the facelet node tree
procedure Update (Factory : in out Facelet_Factory;
Facelet : in Facelet_Access);
-- ------------------------------
-- Returns True if the facelet is null/empty.
-- ------------------------------
function Is_Null (F : Facelet) return Boolean is
begin
return F.Facelet = null;
end Is_Null;
-- ------------------------------
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
-- ------------------------------
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
begin
Log.Debug ("Find facelet {0}", Name);
Find (Factory, Name, Result);
if Result.Facelet = null then
Load (Factory, Name, Context, Result);
if Result.Facelet = null then
return;
end if;
Update (Factory, Result.Facelet);
end if;
end Find_Facelet;
-- ------------------------------
-- Create the component tree from the facelet view.
-- ------------------------------
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access) is
Old : Unbounded_String;
begin
if View.Facelet /= null then
Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.Facelet.File.all),
Previous => Old);
View.Facelet.Root.Build_Children (Parent => Root, Context => Context);
Context.Set_Relative_Path (Path => Old);
end if;
end Build_View;
-- ------------------------------
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
-- ------------------------------
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean) is
begin
Log.Info ("Set facelet search directory to: '{0}'", Paths);
Factory.Factory := Components;
Factory.Paths := To_Unbounded_String (Paths);
Factory.Ignore_White_Spaces := Ignore_White_Spaces;
Factory.Ignore_Empty_Lines := Ignore_Empty_Lines;
Factory.Escape_Unknown_Tags := Escape_Unknown_Tags;
end Initialize;
-- ------------------------------
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
-- ------------------------------
function Find_Facelet_Path (Factory : Facelet_Factory;
Name : String) return String is
begin
return Util.Files.Find_File_Path (Name, To_String (Factory.Paths));
end Find_Facelet_Path;
-- ------------------------------
-- Find in the factory for the facelet with the given name.
-- ------------------------------
procedure Find (Factory : in out Facelet_Factory;
Name : in String;
Result : out Facelet) is
use Ada.Directories;
use Ada.Calendar;
begin
Result.Facelet := Factory.Map.Find (Name);
if Result.Facelet /= null then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Result.Facelet.Check_Time < Now then
if Modification_Time (Result.Facelet.File.Path) > Result.Facelet.Modify_Time then
Log.Info ("Ignoring cache because file '{0}' was modified",
Result.Facelet.File.Path);
Result.Facelet := null;
else
Result.Facelet.Check_Time := Now + CHECK_FILE_DELAY;
end if;
end if;
end;
end if;
end Find;
-- ------------------------------
-- Load the facelet node tree by reading the facelet XHTML file.
-- ------------------------------
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Path : constant String := Find_Facelet_Path (Factory, Name);
begin
if Path = "" or else not Ada.Directories.Exists (Path) then
Log.Warn ("Cannot read '{0}': file does not exist", Path);
Result.Facelet := null;
return;
end if;
declare
use type Ada.Calendar.Time;
Pos : constant Integer := Path'Last - Name'Length + 1;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock + CHECK_FILE_DELAY;
File : File_Info_Access;
Reader : ASF.Views.Nodes.Reader.Xhtml_Reader;
Read : Input_Sources.File.File_Input;
Mtime : Ada.Calendar.Time;
Ctx : aliased EL.Contexts.Default.Default_Context;
Root : ASF.Views.Nodes.Tag_Node_Access;
begin
if Pos <= Path'First then
File := Create_File_Info (Path, Path'First);
else
File := Create_File_Info (Path, Pos);
end if;
Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name,
Natural'Image (File.Relative_Pos));
Ctx.Set_Function_Mapper (Context.Get_Function_Mapper);
Mtime := Ada.Directories.Modification_Time (Path);
Input_Sources.File.Open (Path, Read);
-- If True, xmlns:* attributes will be reported in Start_Element
Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False);
Reader.Set_Feature (Sax.Readers.Validation_Feature, False);
Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces);
Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags);
Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines);
begin
Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access);
exception
when ASF.Views.Nodes.Reader.Parsing_Error =>
Free (File);
when E : others =>
Free (File);
Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path,
Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E));
end;
Root := Reader.Get_Root;
if File = null then
if Root /= null then
Root.Delete;
end if;
Result.Facelet := null;
else
Result.Facelet := new Facelet_Type '(Util.Refs.Ref_Entity with
Len => Name'Length,
Root => Root,
File => File,
Modify_Time => Mtime,
Check_Time => Now,
Name => Name);
end if;
Input_Sources.File.Close (Read);
end;
end Load;
-- ------------------------------
-- Update the factory to store the facelet node tree
-- ------------------------------
procedure Update (Factory : in out Facelet_Factory;
Facelet : in Facelet_Access) is
begin
Factory.Map.Insert (Facelet);
end Update;
-- ------------------------------
-- Clear the facelet cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Facelet_Factory) is
begin
Log.Info ("Clearing facelet cache");
Factory.Map.Clear;
end Clear_Cache;
protected body Facelet_Cache is
-- ------------------------------
-- Find the facelet entry associated with the given name.
-- ------------------------------
function Find (Name : in String) return Facelet_Access is
Key : aliased Facelet_Type := Facelet_Type '(Util.Refs.Ref_Entity with
Len => Name'Length,
Name => Name,
others => <>);
Pos : constant Facelet_Sets.Cursor := Map.Find (Key'Unchecked_Access);
begin
if Facelet_Sets.Has_Element (Pos) then
return Element (Pos);
else
return null;
end if;
end Find;
-- ------------------------------
-- Insert or replace the facelet entry associated with the given name.
-- ------------------------------
procedure Insert (Facelet : in Facelet_Access) is
begin
Map.Include (Facelet);
end Insert;
-- ------------------------------
-- Clear the cache.
-- ------------------------------
procedure Clear is
begin
loop
declare
Pos : Facelet_Sets.Cursor := Map.First;
Node : Facelet_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Map.Delete (Pos);
Free (Node.File);
ASF.Views.Nodes.Destroy (Node.Root);
Free (Node);
end;
end loop;
end Clear;
end Facelet_Cache;
-- ------------------------------
-- Free the storage held by the factory cache.
-- ------------------------------
overriding
procedure Finalize (Factory : in out Facelet_Factory) is
begin
Factory.Clear_Cache;
end Finalize;
end ASF.Views.Facelets;
|
Fix Find procedure when the facelet cache is ignored
|
Fix Find procedure when the facelet cache is ignored
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b7d7a4df8847da5d3c88638a7c639df4606dd046
|
orka_plugin_atmosphere/src/orka-features-atmosphere-rendering.adb
|
orka_plugin_atmosphere/src/orka-features-atmosphere-rendering.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Numerics.Generic_Elementary_Functions;
with GL.Buffers;
with Orka.Rendering.Drawing;
with Orka.Transforms.Doubles.Matrices;
with Orka.Transforms.Doubles.Vectors;
with Orka.Transforms.Doubles.Vector_Conversions;
with Orka.Transforms.Singles.Vectors;
package body Orka.Features.Atmosphere.Rendering is
package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double);
Altitude_Hack_Threshold : constant := 8000.0;
function Create_Atmosphere
(Data : aliased Model_Data;
Location : Resources.Locations.Location_Ptr;
Parameters : Model_Parameters := (others => <>)) return Atmosphere
is
Atmosphere_Model : constant Model := Create_Model (Data'Access, Location);
Sky_GLSL : constant String := Resources.Convert
(Orka.Resources.Byte_Array'(Location.Read_Data ("atmosphere/sky.frag").Get));
use Ada.Characters.Latin_1;
use Rendering.Programs;
use Rendering.Programs.Modules;
Sky_Shader : constant String :=
"#version 420 core" & LF &
(if Data.Luminance /= None then "#define USE_LUMINANCE" & LF else "") &
"const float kLengthUnitInMeters = " & Data.Length_Unit_In_Meters'Image & ";" & LF &
Sky_GLSL & LF;
Shader_Module : constant Rendering.Programs.Modules.Module := Atmosphere_Model.Get_Shader;
begin
return Result : Atmosphere :=
(Program => Create_Program (Modules.Module_Array'
(Modules.Create_Module (Location, VS => "atmosphere/sky.vert"),
Modules.Create_Module_From_Sources (FS => Sky_Shader),
Shader_Module)),
Module => Shader_Module,
Parameters => Parameters,
Bottom_Radius => Data.Bottom_Radius,
Distance_Scale => 1.0 / Data.Length_Unit_In_Meters,
others => <>)
do
Result.Uniform_Ground_Hack := Result.Program.Uniform ("ground_hack");
Result.Uniform_Camera_Offset := Result.Program.Uniform ("camera_offset");
Result.Uniform_Camera_Pos := Result.Program.Uniform ("camera_pos");
Result.Uniform_Planet_Pos := Result.Program.Uniform ("planet_pos");
Result.Uniform_View := Result.Program.Uniform ("view");
Result.Uniform_Proj := Result.Program.Uniform ("proj");
Result.Uniform_Sun_Dir := Result.Program.Uniform ("sun_direction");
Result.Uniform_Star_Dir := Result.Program.Uniform ("star_direction");
Result.Uniform_Star_Size := Result.Program.Uniform ("star_size");
end return;
end Create_Atmosphere;
function Shader_Module (Object : Atmosphere) return Orka.Rendering.Programs.Modules.Module is
(Object.Module);
function Flattened_Vector
(Parameters : Model_Parameters;
Direction : Orka.Transforms.Doubles.Vectors.Vector4)
return Orka.Transforms.Doubles.Vectors.Vector4 is
Altitude : constant := 0.0;
Flattening : GL.Types.Double renames Parameters.Flattening;
E2 : constant GL.Types.Double := 2.0 * Flattening - Flattening**2;
N : constant GL.Types.Double := Parameters.Semi_Major_Axis /
EF.Sqrt (1.0 - E2 * Direction (Orka.Z)**2);
begin
return
(Direction (Orka.X) * (N + Altitude),
Direction (Orka.Y) * (N + Altitude),
Direction (Orka.Z) * (N * (1.0 - E2) + Altitude),
1.0);
end Flattened_Vector;
package Matrices renames Orka.Transforms.Doubles.Matrices;
procedure Render
(Object : in out Atmosphere;
Camera : Cameras.Camera_Ptr;
Planet : Behaviors.Behavior_Ptr;
Star : Behaviors.Behavior_Ptr)
is
function "*" (Left : Matrices.Matrix4; Right : Matrices.Vector4) return Matrices.Vector4
renames Matrices."*";
function "*" (Left, Right : Matrices.Matrix4) return Matrices.Matrix4 renames Matrices."*";
function Far_Plane (Value : GL.Types.Compare_Function) return GL.Types.Compare_Function is
(case Value is
when Less | LEqual => LEqual,
when Greater | GEqual => GEqual,
when others => raise Constraint_Error);
Original_Function : constant GL.Types.Compare_Function := GL.Buffers.Depth_Function;
use Orka.Transforms.Doubles.Vectors;
use Orka.Transforms.Doubles.Vector_Conversions;
use all type Orka.Transforms.Doubles.Vectors.Vector4;
Planet_To_Camera : constant Vector4 := Camera.View_Position - Planet.Position;
Planet_To_Star : constant Vector4 := Star.Position - Planet.Position;
Camera_To_Star : constant Vector4 := Star.Position - Camera.View_Position;
procedure Apply_Hacks is
GL_To_Geo : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 1.0, 1.0, 0.0)),
(2.0 / 3.0) * Ada.Numerics.Pi);
Earth_Tilt : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 0.0, 0.0, 0.0)),
Object.Parameters.Axial_Tilt);
Inverse_Inertial : constant Matrices.Matrix4 := Earth_Tilt * GL_To_Geo;
Camera_Normal_Inert : constant Vector4 := Normalize (Inverse_Inertial * Planet_To_Camera);
Actual_Surface : constant Vector4 := Flattened_Vector
(Object.Parameters, Camera_Normal_Inert);
Expected_Surface : constant Vector4 := Camera_Normal_Inert * Object.Bottom_Radius;
Offset : constant Vector4 := Expected_Surface - Actual_Surface;
Altitude : constant Double := Length (Planet_To_Camera) - Length (Actual_Surface);
begin
Object.Uniform_Ground_Hack.Set_Boolean (Altitude < Altitude_Hack_Threshold);
Object.Uniform_Camera_Offset.Set_Vector (Convert (Offset * Object.Distance_Scale));
end Apply_Hacks;
begin
if Object.Parameters.Flattening > 0.0 then
Apply_Hacks;
else
Object.Uniform_Ground_Hack.Set_Boolean (False);
Object.Uniform_Camera_Offset.Set_Vector (Orka.Transforms.Singles.Vectors.Zero);
end if;
Object.Uniform_Camera_Pos.Set_Vector (Orka.Transforms.Singles.Vectors.Zero);
Object.Uniform_Planet_Pos.Set_Vector (Convert (-Planet_To_Camera * Object.Distance_Scale));
Object.Uniform_Sun_Dir.Set_Vector (Convert (Normalize (Planet_To_Star)));
Object.Uniform_Star_Dir.Set_Vector (Convert (Normalize (Camera_To_Star)));
-- Use distance to star and its radius instead of the
-- Sun_Angular_Radius of Model_Data
declare
Angular_Radius : constant GL.Types.Double :=
EF.Arctan (Object.Parameters.Star_Radius, Length (Camera_To_Star));
begin
Object.Uniform_Star_Size.Set_Single (GL.Types.Single (EF.Cos (Angular_Radius)));
end;
Object.Uniform_View.Set_Matrix (Camera.View_Matrix);
Object.Uniform_Proj.Set_Matrix (Camera.Projection_Matrix);
Object.Program.Use_Program;
GL.Buffers.Set_Depth_Function (Far_Plane (Original_Function));
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
GL.Buffers.Set_Depth_Function (Original_Function);
end Render;
end Orka.Features.Atmosphere.Rendering;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Numerics.Generic_Elementary_Functions;
with GL.Buffers;
with Orka.Rendering.Drawing;
with Orka.Transforms.Doubles.Matrices;
with Orka.Transforms.Doubles.Vectors;
with Orka.Transforms.Doubles.Vector_Conversions;
with Orka.Transforms.Singles.Vectors;
package body Orka.Features.Atmosphere.Rendering is
package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double);
Altitude_Hack_Threshold : constant := 8000.0;
function Create_Atmosphere
(Data : aliased Model_Data;
Location : Resources.Locations.Location_Ptr;
Parameters : Model_Parameters := (others => <>)) return Atmosphere
is
Atmosphere_Model : constant Model := Create_Model (Data'Access, Location);
Sky_GLSL : constant String := Resources.Convert
(Orka.Resources.Byte_Array'(Location.Read_Data ("atmosphere/sky.frag").Get));
use Ada.Characters.Latin_1;
use Rendering.Programs;
use Rendering.Programs.Modules;
Sky_Shader : constant String :=
"#version 420 core" & LF &
(if Data.Luminance /= None then "#define USE_LUMINANCE" & LF else "") &
"const float kLengthUnitInMeters = " & Data.Length_Unit_In_Meters'Image & ";" & LF &
Sky_GLSL & LF;
Shader_Module : constant Rendering.Programs.Modules.Module := Atmosphere_Model.Get_Shader;
begin
return Result : Atmosphere :=
(Program => Create_Program (Modules.Module_Array'
(Modules.Create_Module (Location, VS => "atmosphere/sky.vert"),
Modules.Create_Module_From_Sources (FS => Sky_Shader),
Shader_Module)),
Module => Shader_Module,
Parameters => Parameters,
Bottom_Radius => Data.Bottom_Radius,
Distance_Scale => 1.0 / Data.Length_Unit_In_Meters,
others => <>)
do
Result.Uniform_Ground_Hack := Result.Program.Uniform ("ground_hack");
Result.Uniform_Camera_Offset := Result.Program.Uniform ("camera_offset");
Result.Uniform_Camera_Pos := Result.Program.Uniform ("camera_pos");
Result.Uniform_Planet_Pos := Result.Program.Uniform ("planet_pos");
Result.Uniform_View := Result.Program.Uniform ("view");
Result.Uniform_Proj := Result.Program.Uniform ("proj");
Result.Uniform_Sun_Dir := Result.Program.Uniform ("sun_direction");
Result.Uniform_Star_Dir := Result.Program.Uniform ("star_direction");
Result.Uniform_Star_Size := Result.Program.Uniform ("star_size");
end return;
end Create_Atmosphere;
function Shader_Module (Object : Atmosphere) return Orka.Rendering.Programs.Modules.Module is
(Object.Module);
function Flattened_Vector
(Parameters : Model_Parameters;
Direction : Orka.Transforms.Doubles.Vectors.Vector4)
return Orka.Transforms.Doubles.Vectors.Vector4 is
Altitude : constant := 0.0;
Flattening : GL.Types.Double renames Parameters.Flattening;
E2 : constant GL.Types.Double := 2.0 * Flattening - Flattening**2;
N : constant GL.Types.Double := Parameters.Semi_Major_Axis /
EF.Sqrt (1.0 - E2 * Direction (Orka.Z)**2);
begin
return
(Direction (Orka.X) * (N + Altitude),
Direction (Orka.Y) * (N + Altitude),
Direction (Orka.Z) * (N * (1.0 - E2) + Altitude),
1.0);
end Flattened_Vector;
package Matrices renames Orka.Transforms.Doubles.Matrices;
procedure Render
(Object : in out Atmosphere;
Camera : Cameras.Camera_Ptr;
Planet : Behaviors.Behavior_Ptr;
Star : Behaviors.Behavior_Ptr)
is
function "*" (Left : Matrices.Matrix4; Right : Matrices.Vector4) return Matrices.Vector4
renames Matrices."*";
function "*" (Left, Right : Matrices.Matrix4) return Matrices.Matrix4 renames Matrices."*";
function Far_Plane (Value : GL.Types.Compare_Function) return GL.Types.Compare_Function is
(case Value is
when Less | LEqual => LEqual,
when Greater | GEqual => GEqual,
when others => raise Constraint_Error);
Original_Function : constant GL.Types.Compare_Function := GL.Buffers.Depth_Function;
use Orka.Transforms.Doubles.Vectors;
use Orka.Transforms.Doubles.Vector_Conversions;
use all type Orka.Transforms.Doubles.Vectors.Vector4;
Planet_To_Camera : constant Vector4 := Camera.View_Position - Planet.Position;
Planet_To_Star : constant Vector4 := Star.Position - Planet.Position;
Camera_To_Star : constant Vector4 := Star.Position - Camera.View_Position;
procedure Apply_Hacks is
GL_To_Geo : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 1.0, 1.0, 0.0)),
(2.0 / 3.0) * Ada.Numerics.Pi);
Earth_Tilt : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 0.0, 0.0, 0.0)),
Object.Parameters.Axial_Tilt);
Inverse_Inertial : constant Matrices.Matrix4 := Earth_Tilt * GL_To_Geo;
Camera_Normal_Inert : constant Vector4 := Normalize (Inverse_Inertial * Planet_To_Camera);
Actual_Surface : constant Vector4 := Flattened_Vector
(Object.Parameters, Camera_Normal_Inert);
Expected_Surface : constant Vector4 := Camera_Normal_Inert * Object.Bottom_Radius;
Offset : constant Vector4 := Expected_Surface - Actual_Surface;
Altitude : constant Double := Length (Planet_To_Camera) - Length (Actual_Surface);
begin
Object.Uniform_Ground_Hack.Set_Boolean (Altitude < Altitude_Hack_Threshold);
Object.Uniform_Camera_Offset.Set_Vector (Convert (Offset * Object.Distance_Scale));
end Apply_Hacks;
begin
if Object.Parameters.Flattening > 0.0 then
Apply_Hacks;
else
Object.Uniform_Ground_Hack.Set_Boolean (False);
Object.Uniform_Camera_Offset.Set_Vector (Orka.Transforms.Singles.Vectors.Zero_Vector);
end if;
Object.Uniform_Camera_Pos.Set_Vector (Orka.Transforms.Singles.Vectors.Zero_Vector);
Object.Uniform_Planet_Pos.Set_Vector (Convert (-Planet_To_Camera * Object.Distance_Scale));
Object.Uniform_Sun_Dir.Set_Vector (Convert (Normalize (Planet_To_Star)));
Object.Uniform_Star_Dir.Set_Vector (Convert (Normalize (Camera_To_Star)));
-- Use distance to star and its radius instead of the
-- Sun_Angular_Radius of Model_Data
declare
Angular_Radius : constant GL.Types.Double :=
EF.Arctan (Object.Parameters.Star_Radius, Length (Camera_To_Star));
begin
Object.Uniform_Star_Size.Set_Single (GL.Types.Single (EF.Cos (Angular_Radius)));
end;
Object.Uniform_View.Set_Matrix (Camera.View_Matrix);
Object.Uniform_Proj.Set_Matrix (Camera.Projection_Matrix);
Object.Program.Use_Program;
GL.Buffers.Set_Depth_Function (Far_Plane (Original_Function));
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
GL.Buffers.Set_Depth_Function (Original_Function);
end Render;
end Orka.Features.Atmosphere.Rendering;
|
Fix compilation after renaming function to a constant
|
atmosphere: Fix compilation after renaming function to a constant
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
5ddd176ba7e6b0599f4f15145a5a25af4a6d90f1
|
src/asf-components-html-pages.adb
|
src/asf-components-html-pages.adb
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Beans.Objects;
with ASF.Utils;
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package body ASF.Components.Html.Pages is
BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Head Component
-- ------------------------------
-- ------------------------------
-- Encode the HTML head element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("head");
UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("head");
end Encode_End;
-- ------------------------------
-- Encode the HTML body element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("body");
UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
-- ------------------------------
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("body");
end Encode_End;
-- ------------------------------
-- Encode the DOCTYPE element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Write ("<!DOCTYPE ");
Writer.Write (UI.Get_Attribute ("rootElement", Context, ""));
declare
Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public");
System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system");
begin
if not Util.Beans.Objects.Is_Null (Public) then
Writer.Write (" PUBLIC """);
Writer.Write (Public);
Writer.Write ('"');
end if;
if not Util.Beans.Objects.Is_Null (System) then
Writer.Write (" """);
Writer.Write (System);
Writer.Write ('"');
end if;
end;
Writer.Write ('>');
Writer.Write (ASCII.LF);
end if;
end Encode_Begin;
begin
Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES);
Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES);
end ASF.Components.Html.Pages;
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 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 Util.Strings;
with Util.Beans.Objects;
with ASF.Utils;
with ASF.Requests;
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package body ASF.Components.Html.Pages is
BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Head Component
-- ------------------------------
-- ------------------------------
-- Encode the HTML head element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("head");
UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("head");
end Encode_End;
-- ------------------------------
-- Encode the HTML body element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("body");
UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
-- ------------------------------
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("body");
end Encode_End;
-- ------------------------------
-- Get the link to be rendered in the <b>href</b> attribute.
-- ------------------------------
function Get_Link (UI : in UIOutputStylesheet;
Context : in Faces_Context'Class) return String is
Req : constant ASF.Requests.Request_Access := Context.Get_Request;
Name : constant String := UI.Get_Attribute ("name", Context, "");
Lib : constant String := UI.Get_Attribute ("library", Context, "");
Ctx : constant String := Req.Get_Context_Path;
begin
if Lib'Length > 0 then
return Ctx & "/resources/" & Lib & "/" & Name;
else
return Ctx & "/resources/" & Name;
end if;
end Get_Link;
-- ------------------------------
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
-- ------------------------------
overriding
procedure Encode_End (UI : in UIOutputStylesheet;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
Writer.Start_Element ("link");
Writer.Write_Attribute ("type", "text/css");
Writer.Write_Attribute ("rel", "stylesheet");
Writer.Write_Attribute ("href", UI.Get_Link (Context));
Writer.End_Element ("link");
end Encode_End;
-- ------------------------------
-- Encode the DOCTYPE element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Write ("<!DOCTYPE ");
Writer.Write (UI.Get_Attribute ("rootElement", Context, ""));
declare
Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public");
System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system");
begin
if not Util.Beans.Objects.Is_Null (Public) then
Writer.Write (" PUBLIC """);
Writer.Write (Public);
Writer.Write ('"');
end if;
if not Util.Beans.Objects.Is_Null (System) then
Writer.Write (" """);
Writer.Write (System);
Writer.Write ('"');
end if;
end;
Writer.Write ('>');
Writer.Write (ASCII.LF);
end if;
end Encode_Begin;
begin
Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES);
Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES);
end ASF.Components.Html.Pages;
|
Implement Encode_End and Get_Link for UIOutputStylesheet type
|
Implement Encode_End and Get_Link for UIOutputStylesheet type
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c7b6cc2177b7cc32a0888bee5808166b1910afad
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
--
-- -- Returns true if the given role is stored in the user principal.
-- function Has_Role (User : in Principal;
-- Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Move the Principal to the Security package
|
Move the Principal to the Security package
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
05530c58a537231712971969b9314b6919ab1323
|
src/core/strings/util-strings.ads
|
src/core/strings/util-strings.ads
|
-----------------------------------------------------------------------
-- util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 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 Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
private with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns True if the source string starts with the given prefix.
function Starts_With (Source : in String;
Prefix : in String) return Boolean;
-- Returns True if the source string ends with the given suffix.
function Ends_With (Source : in String;
Suffix : in String) return Boolean;
-- Returns True if the source contains the pattern.
function Contains (Source : in String;
Pattern : in String) return Boolean;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
-----------------------------------------------------------------------
-- util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
private with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns True if the source string starts with the given prefix.
function Starts_With (Source : in String;
Prefix : in String) return Boolean;
-- Returns True if the source string ends with the given suffix.
function Ends_With (Source : in String;
Suffix : in String) return Boolean;
-- Returns True if the source contains the pattern.
function Contains (Source : in String;
Pattern : in String) return Boolean;
-- Simple string replacement within the source of the specified content
-- by another string. By default, replace only the first sequence.
function Replace (Source : in String;
Content : in String;
By : in String;
First : in Boolean := True) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
Add the Replace function to replace a content by another one
|
Add the Replace function to replace a content by another one
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0e8b5731743b280a0214b9f9487e9ef04be5009c
|
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;
with Security.Permissions;
-- == 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.
--
-- == Step 1: 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);
--
-- == Step 2: verify 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.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- 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.Permissions.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;
with Security.Permissions;
-- == 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]
--
-- == Step 1: 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);
--
-- == Step 2: verify 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.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- 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.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Add picture
|
Add picture
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
2ddbdd7b688142d47ea8738224747233c34fd3ba
|
src/util-events-timers.adb
|
src/util-events-timers.adb
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list 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.Unchecked_Deallocation;
package body Util.Events.Timers is
use type Ada.Real_Time.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Timer_Node,
Name => Timer_Node_Access);
-- -----------------------
-- Repeat the timer.
-- -----------------------
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span) is
Timer : constant Timer_Node_Access := Event.Value;
begin
if Timer /= null and then Timer.List /= null then
Timer.List.Add (Timer, Timer.Deadline + In_Time);
end if;
end Repeat;
-- -----------------------
-- Cancel the timer.
-- -----------------------
procedure Cancel (Event : in out Timer_Ref) is
begin
if Event.Value /= null and then Event.Value.List /= null then
Event.Value.List.all.Cancel (Event.Value);
Event.Value.List := null;
end if;
end Cancel;
-- -----------------------
-- Check if the timer is ready to be executed.
-- -----------------------
function Is_Scheduled (Event : in Timer_Ref) return Boolean is
begin
return Event.Value /= null and then Event.Value.List /= null;
end Is_Scheduled;
-- -----------------------
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
-- -----------------------
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is
begin
return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last);
end Time_Of_Event;
-- -----------------------
-- Set a timer to be called at the given time.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time) is
Timer : Timer_Node_Access := Event.Value;
begin
if Timer = null then
Event.Value := new Timer_Node;
Timer := Event.Value;
end if;
Timer.Handler := Handler;
-- Cancel the timer if it is part of another timer manager.
if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then
Timer.List.Cancel (Timer);
end if;
-- Update the timer.
Timer.List := List.Manager'Unchecked_Access;
List.Manager.Add (Timer, At_Time);
end Set_Timer;
-- -----------------------
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
-- -----------------------
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last) is
Timer : Timer_Ref;
Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
loop
Timer.Finalize;
List.Manager.Find_Next (Now, Timeout, Timer);
exit when not Timer.Is_Scheduled;
Timer.Value.Handler.Time_Handler (Timer);
end loop;
end Process;
overriding
procedure Adjust (Object : in out Timer_Ref) is
begin
if Object.Value /= null then
Util.Concurrent.Counters.Increment (Object.Value.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Timer_Ref) is
Is_Zero : Boolean;
begin
if Object.Value /= null then
Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero);
if Is_Zero then
Free (Object.Value);
else
Object.Value := null;
end if;
end if;
end Finalize;
protected body Timer_Manager is
procedure Remove (Timer : in Timer_Node_Access) is
begin
if List = Timer then
List := Timer.Next;
Timer.Prev := null;
if List /= null then
List.Prev := null;
end if;
elsif Timer.Prev /= null then
Timer.Prev.Next := Timer.Next;
Timer.Next.Prev := Timer.Prev;
else
return;
end if;
Timer.Next := null;
Timer.Prev := null;
Timer.List := null;
end Remove;
-- -----------------------
-- Add a timer.
-- -----------------------
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time) is
Current : Timer_Node_Access := List;
Prev : Timer_Node_Access;
begin
Util.Concurrent.Counters.Increment (Timer.Counter);
if Timer.List /= null then
Remove (Timer);
end if;
Timer.Deadline := Deadline;
while Current /= null loop
if Current.Deadline < Deadline then
if Prev = null then
List := Timer;
else
Prev.Next := Timer;
end if;
Timer.Next := Current;
Current.Prev := Timer;
return;
end if;
Prev := Current;
Current := Current.Next;
end loop;
if Prev = null then
List := Timer;
Timer.Prev := null;
else
Prev.Next := Timer;
Timer.Prev := Prev;
end if;
Timer.Next := null;
end Add;
-- -----------------------
-- Cancel a timer.
-- -----------------------
procedure Cancel (Timer : in out Timer_Node_Access) is
Is_Zero : Boolean;
begin
if Timer.List = null then
return;
end if;
Remove (Timer);
Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero);
if Is_Zero then
Free (Timer);
end if;
end Cancel;
-- -----------------------
-- Find the next timer to be executed before the given time or return the next deadline.
-- -----------------------
procedure Find_Next (Before : in Ada.Real_Time.Time;
Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref) is
begin
if List = null then
Deadline := Ada.Real_Time.Time_Last;
elsif List.Deadline < Before then
Timer.Value := List;
List := List.Next;
if List /= null then
List.Prev := null;
Deadline := List.Deadline;
else
Deadline := Ada.Real_Time.Time_Last;
end if;
else
Deadline := List.Deadline;
end if;
end Find_Next;
end Timer_Manager;
overriding
procedure Finalize (Object : in out Timer_List) is
Timer : Timer_Ref;
Timeout : Ada.Real_Time.Time;
begin
loop
Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer);
exit when Timer.Value = null;
Timer.Finalize;
end loop;
end Finalize;
end Util.Events.Timers;
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list 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.Unchecked_Deallocation;
package body Util.Events.Timers is
use type Ada.Real_Time.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Timer_Node,
Name => Timer_Node_Access);
-- -----------------------
-- Repeat the timer.
-- -----------------------
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span) is
Timer : constant Timer_Node_Access := Event.Value;
begin
if Timer /= null and then Timer.List /= null then
Timer.List.Add (Timer, Timer.Deadline + In_Time);
end if;
end Repeat;
-- -----------------------
-- Cancel the timer.
-- -----------------------
procedure Cancel (Event : in out Timer_Ref) is
begin
if Event.Value /= null and then Event.Value.List /= null then
Event.Value.List.all.Cancel (Event.Value);
Event.Value.List := null;
end if;
end Cancel;
-- -----------------------
-- Check if the timer is ready to be executed.
-- -----------------------
function Is_Scheduled (Event : in Timer_Ref) return Boolean is
begin
return Event.Value /= null and then Event.Value.List /= null;
end Is_Scheduled;
-- -----------------------
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
-- -----------------------
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is
begin
return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last);
end Time_Of_Event;
-- -----------------------
-- Set a timer to be called at the given time.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time) is
Timer : Timer_Node_Access := Event.Value;
begin
if Timer = null then
Event.Value := new Timer_Node;
Timer := Event.Value;
end if;
Timer.Handler := Handler;
-- Cancel the timer if it is part of another timer manager.
if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then
Timer.List.Cancel (Timer);
end if;
-- Update the timer.
Timer.List := List.Manager'Unchecked_Access;
List.Manager.Add (Timer, At_Time);
end Set_Timer;
-- -----------------------
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
-- -----------------------
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last) is
Timer : Timer_Ref;
Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
loop
List.Manager.Find_Next (Now, Timeout, Timer);
exit when Timer.Value = null;
Timer.Value.Handler.Time_Handler (Timer);
Timer.Finalize;
end loop;
end Process;
overriding
procedure Adjust (Object : in out Timer_Ref) is
begin
if Object.Value /= null then
Util.Concurrent.Counters.Increment (Object.Value.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Timer_Ref) is
Is_Zero : Boolean;
begin
if Object.Value /= null then
Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero);
if Is_Zero then
Free (Object.Value);
else
Object.Value := null;
end if;
end if;
end Finalize;
protected body Timer_Manager is
procedure Remove (Timer : in Timer_Node_Access) is
begin
if List = Timer then
List := Timer.Next;
Timer.Prev := null;
if List /= null then
List.Prev := null;
end if;
elsif Timer.Prev /= null then
Timer.Prev.Next := Timer.Next;
Timer.Next.Prev := Timer.Prev;
else
return;
end if;
Timer.Next := null;
Timer.Prev := null;
Timer.List := null;
end Remove;
-- -----------------------
-- Add a timer.
-- -----------------------
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time) is
Current : Timer_Node_Access := List;
Prev : Timer_Node_Access;
begin
Util.Concurrent.Counters.Increment (Timer.Counter);
if Timer.List /= null then
Remove (Timer);
end if;
Timer.Deadline := Deadline;
while Current /= null loop
if Current.Deadline < Deadline then
if Prev = null then
List := Timer;
else
Prev.Next := Timer;
end if;
Timer.Next := Current;
Current.Prev := Timer;
return;
end if;
Prev := Current;
Current := Current.Next;
end loop;
if Prev = null then
List := Timer;
Timer.Prev := null;
else
Prev.Next := Timer;
Timer.Prev := Prev;
end if;
Timer.Next := null;
end Add;
-- -----------------------
-- Cancel a timer.
-- -----------------------
procedure Cancel (Timer : in out Timer_Node_Access) is
Is_Zero : Boolean;
begin
if Timer.List = null then
return;
end if;
Remove (Timer);
Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero);
if Is_Zero then
Free (Timer);
end if;
end Cancel;
-- -----------------------
-- Find the next timer to be executed before the given time or return the next deadline.
-- -----------------------
procedure Find_Next (Before : in Ada.Real_Time.Time;
Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref) is
begin
if List = null then
Deadline := Ada.Real_Time.Time_Last;
elsif List.Deadline < Before then
Timer.Value := List;
List := List.Next;
if List /= null then
List.Prev := null;
Deadline := List.Deadline;
else
Deadline := Ada.Real_Time.Time_Last;
end if;
else
Deadline := List.Deadline;
end if;
end Find_Next;
end Timer_Manager;
overriding
procedure Finalize (Object : in out Timer_List) is
Timer : Timer_Ref;
Timeout : Ada.Real_Time.Time;
begin
loop
Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer);
exit when Timer.Value = null;
Timer.Finalize;
end loop;
end Finalize;
end Util.Events.Timers;
|
Update the Process procedure to finalize the timer only after execution of the timer handler
|
Update the Process procedure to finalize the timer only after execution of the timer handler
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
13031ecd19f67a524baf6491cd66f24e21baf0ea
|
orka/src/orka/implementation/orka-containers-bounded_vectors.adb
|
orka/src/orka/implementation/orka-containers-bounded_vectors.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Containers.Bounded_Vectors is
function Length (Container : Vector) return Length_Type is
(Container.Length);
function Is_Empty (Container : Vector) return Boolean is
(Length (Container) = 0);
function Is_Full (Container : Vector) return Boolean is
(Length (Container) = Container.Capacity);
procedure Append (Container : in out Vector; Elements : Vector) is
Start_Index : constant Index_Type := Container.Length + Index_Type'First;
Stop_Index : constant Index_Type'Base := Start_Index + Elements.Length - 1;
procedure Copy_Elements (Elements : Element_Array) is
begin
Container.Elements (Start_Index .. Stop_Index) := Elements;
end Copy_Elements;
begin
Elements.Query (Copy_Elements'Access);
Container.Length := Container.Length + Elements.Length;
end Append;
procedure Append (Container : in out Vector; Element : Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First;
begin
Container.Length := Container.Length + 1;
Container.Elements (Index) := Element;
end Append;
procedure Remove_Last (Container : in out Vector; Element : out Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First - 1;
begin
Element := Container.Elements (Index);
Container.Elements (Index .. Index) := (others => <>);
Container.Length := Container.Length - 1;
end Remove_Last;
procedure Clear (Container : in out Vector) is
begin
Container.Elements := (others => <>);
Container.Length := 0;
end Clear;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array))
is
Last_Index : constant Index_Type'Base := Container.Length + Index_Type'First - 1;
begin
Process (Container.Elements (Index_Type'First .. Last_Index));
end Query;
procedure Update
(Container : in out Vector;
Index : Index_Type;
Process : not null access procedure (Element : in out Element_Type)) is
begin
Process (Container.Elements (Index));
end Update;
function Element (Container : Vector; Index : Index_Type) return Element_Type is
(Container.Elements (Index));
function Element (Container : aliased Vector; Position : Cursor) return Element_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object /= Container'Access then
raise Program_Error;
else
return Element (Container, Position.Index);
end if;
end Element;
function Constant_Reference
(Container : aliased Vector;
Index : Index_Type) return Constant_Reference_Type is
begin
return Constant_Reference_Type'(Value => Container.Elements (Index)'Access);
end Constant_Reference;
function Constant_Reference
(Container : aliased Vector;
Position : Cursor) return Constant_Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object /= Container'Access then
raise Program_Error;
else
return Constant_Reference (Container, Position.Index);
end if;
end Constant_Reference;
function Reference
(Container : aliased in out Vector;
Index : Index_Type) return Reference_Type is
begin
return Reference_Type'(Value => Container.Elements (Index)'Access);
end Reference;
function Reference
(Container : aliased in out Vector;
Position : Cursor) return Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object /= Container'Access then
raise Program_Error;
else
return Reference (Container, Position.Index);
end if;
end Reference;
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Iterator'(Container => Container'Unchecked_Access);
end Iterate;
overriding function First (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container, Index => Index_Type'First);
end if;
end First;
overriding function Last (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container,
Index => Object.Container.all.Length);
end if;
end Last;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Position.Object.Length + Index_Type'First - 1 then
return No_Element;
else
return Cursor'(Position.Object, Position.Index + 1);
end if;
end Next;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Index_Type'First then
return No_Element;
else
return Cursor'(Position.Object, Position.Index - 1);
end if;
end Previous;
end Orka.Containers.Bounded_Vectors;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Containers.Bounded_Vectors is
function Length (Container : Vector) return Length_Type is
(Container.Length);
function Is_Empty (Container : Vector) return Boolean is
(Length (Container) = 0);
function Is_Full (Container : Vector) return Boolean is
(Length (Container) = Container.Capacity);
procedure Append (Container : in out Vector; Elements : Vector) is
Start_Index : constant Index_Type := Container.Length + Index_Type'First;
Stop_Index : constant Index_Type'Base := Start_Index + Elements.Length - 1;
procedure Copy_Elements (Elements : Element_Array) is
begin
Container.Elements (Start_Index .. Stop_Index) := Elements;
end Copy_Elements;
begin
Elements.Query (Copy_Elements'Access);
Container.Length := Container.Length + Elements.Length;
end Append;
procedure Append (Container : in out Vector; Element : Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First;
begin
Container.Length := Container.Length + 1;
Container.Elements (Index) := Element;
end Append;
procedure Remove_Last (Container : in out Vector; Element : out Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First - 1;
begin
Element := Container.Elements (Index);
Container.Elements (Index .. Index) := (others => <>);
Container.Length := Container.Length - 1;
end Remove_Last;
procedure Clear (Container : in out Vector) is
begin
Container.Elements := (others => <>);
Container.Length := 0;
end Clear;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array))
is
Last_Index : constant Index_Type'Base := Container.Length + Index_Type'First - 1;
begin
Process (Container.Elements (Index_Type'First .. Last_Index));
end Query;
procedure Update
(Container : in out Vector;
Index : Index_Type;
Process : not null access procedure (Element : in out Element_Type)) is
begin
Process (Container.Elements (Index));
end Update;
function Element (Container : Vector; Index : Index_Type) return Element_Type is
(Container.Elements (Index));
function Element (Container : aliased Vector; Position : Cursor) return Element_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Element (Container, Position.Index);
end if;
end Element;
function Constant_Reference
(Container : aliased Vector;
Index : Index_Type) return Constant_Reference_Type is
begin
return Constant_Reference_Type'(Value => Container.Elements (Index)'Access);
end Constant_Reference;
function Constant_Reference
(Container : aliased Vector;
Position : Cursor) return Constant_Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Constant_Reference (Container, Position.Index);
end if;
end Constant_Reference;
function Reference
(Container : aliased in out Vector;
Index : Index_Type) return Reference_Type is
begin
return Reference_Type'(Value => Container.Elements (Index)'Access);
end Reference;
function Reference
(Container : aliased in out Vector;
Position : Cursor) return Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Reference (Container, Position.Index);
end if;
end Reference;
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Iterator'(Container => Container'Unchecked_Access);
end Iterate;
overriding function First (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container, Index => Index_Type'First);
end if;
end First;
overriding function Last (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container,
Index => Object.Container.all.Length);
end if;
end Last;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Position.Object.Length + Index_Type'First - 1 then
return No_Element;
else
return Cursor'(Position.Object, Position.Index + 1);
end if;
end Next;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Index_Type'First then
return No_Element;
else
return Cursor'(Position.Object, Position.Index - 1);
end if;
end Previous;
end Orka.Containers.Bounded_Vectors;
|
Fix compile error with GNAT CE 2021
|
Fix compile error with GNAT CE 2021
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
b154e896a1a2ed2b8ad8cf811ee503f5699628d6
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value));
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value));
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
Implement the Write_Entity and Write_Attribute for Nullable_String
|
Implement the Write_Entity and Write_Attribute for Nullable_String
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8d7c180772237f65354aa507e1804bd3ddb48b23
|
src/util-streams-buffered.adb
|
src/util-streams-buffered.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.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 : in Output_Stream_Access;
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 : in Input_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
-- Stream.Flush;
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 that the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output = null then
raise Ada.IO_Exceptions.Data_Error with "Output buffer is full";
else
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 : in Output_Stream_Access;
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 : in Input_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- 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;
|
Allow to flush a buffer even if there is no output stream
|
Allow to flush a buffer even if there is no output stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
369bfd1fdcffcfacdeed4432f019a2f397466f8e
|
src/asf-events-exceptions.adb
|
src/asf-events-exceptions.adb
|
-----------------------------------------------------------------------
-- asf-events-exceptions -- Exceptions Events
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Events.Exceptions is
-- ------------------------------
-- Get the exception name.
-- ------------------------------
function Get_Exception_Name (Event : in Exception_Event) return String is
begin
return Ada.Exceptions.Exception_Name (Event.Ex);
end Get_Exception_Name;
-- ------------------------------
-- Get the exception name.
-- ------------------------------
function Get_Exception_Message (Event : in Exception_Event) return String is
begin
return Ada.Exceptions.Exception_Message (Event.Ex);
end Get_Exception_Message;
-- ------------------------------
-- Create an exception event with the given exception.
-- ------------------------------
function Create_Exception_Event (Ex : in Ada.Exceptions.Exception_Occurrence)
return Exception_Event_Access is
Event : Exception_Event_Access := new Exception_Event;
begin
Ada.Exceptions.Save_Occurrence (Target => Event.Ex,
Source => Ex);
return Event;
end Create_Exception_Event;
end ASF.Events.Exceptions;
|
-----------------------------------------------------------------------
-- asf-events-exceptions -- Exceptions Events
-- 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.
-----------------------------------------------------------------------
package body ASF.Events.Exceptions is
-- ------------------------------
-- Get the exception name.
-- ------------------------------
function Get_Exception_Name (Event : in Exception_Event) return String is
begin
return Ada.Exceptions.Exception_Name (Event.Ex);
end Get_Exception_Name;
-- ------------------------------
-- Get the exception name.
-- ------------------------------
function Get_Exception_Message (Event : in Exception_Event) return String is
begin
return Ada.Exceptions.Exception_Message (Event.Ex);
end Get_Exception_Message;
-- ------------------------------
-- Create an exception event with the given exception.
-- ------------------------------
function Create_Exception_Event (Ex : in Ada.Exceptions.Exception_Occurrence)
return Exception_Event_Access is
Event : constant Exception_Event_Access := new Exception_Event;
begin
Ada.Exceptions.Save_Occurrence (Target => Event.Ex,
Source => Ex);
return Event;
end Create_Exception_Event;
end ASF.Events.Exceptions;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
74ff95a7f7e922926693c778bbec9a81647c6b44
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- 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.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Votes.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Votes.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up",
Test_Vote_Up'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Vote_Up (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
Vote_Manager : Vote_Module_Access := Get_Vote_Module;
User : AWA.Users.Models.User_Ref := Context.Get_User;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1);
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2);
end;
end Test_Vote_Up;
end AWA.Votes.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- 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.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Votes.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Votes.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up",
Test_Vote_Up'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Vote_Up (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
Vote_Manager : Vote_Module_Access := Get_Vote_Module;
User : AWA.Users.Models.User_Ref := Context.Get_User;
Total : Integer;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total);
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total);
end;
end Test_Vote_Up;
end AWA.Votes.Modules.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
2d48c8e5821b5ff2bc53b575ea8d5bb277df1321
|
mat/src/mat-targets-probes.adb
|
mat/src/mat-targets-probes.adb
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start 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.Readers.Marshaller;
package body MAT.Targets.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes");
MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0;
MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
M_HEAP_START : constant MAT.Events.Internal_Reference := 3;
M_HEAP_END : constant MAT.Events.Internal_Reference := 4;
M_END : constant MAT.Events.Internal_Reference := 5;
PID_NAME : aliased constant String := "pid";
EXE_NAME : aliased constant String := "exe";
HP_START_NAME : aliased constant String := "hp_start";
HP_END_NAME : aliased constant String := "hp_end";
END_NAME : aliased constant String := "end";
Process_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => PID_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_PID),
2 => (Name => EXE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_EXE),
3 => (Name => HP_START_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START),
4 => (Name => HP_END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END),
5 => (Name => END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_END));
-- ------------------------------
-- Create a new process after the begin event is received from the event stream.
-- ------------------------------
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Probe.Target.Create_Process (Pid => Pid,
Path => Path,
Process => Probe.Target.Current);
Probe.Target.Process.Events := Probe.Events;
MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory,
Manager => Probe.Manager.all);
end Create_Process;
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message) is
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
Heap : MAT.Memory.Region_Info;
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_PID =>
Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg);
when M_HEAP_START =>
Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when M_HEAP_END =>
Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
Heap.Size := Heap.End_Addr - Heap.Start_Addr;
Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]");
Probe.Create_Process (Pid, Path);
Probe.Manager.Read_Message (Msg);
Probe.Manager.Read_Event_Definitions (Msg);
Probe.Target.Process.Memory.Add_Region (Heap);
end Probe_Begin;
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type) is
use type MAT.Events.Targets.Probe_Index_Type;
begin
if Event.Index = MSG_BEGIN then
Probe.Probe_Begin (Event.Index, Params.all, Msg);
end if;
end Extract;
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
null;
end Execute;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access) is
begin
Probe.Manager := Into'Unchecked_Access;
Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "end", MSG_END,
Process_Attributes'Access);
end Register;
-- ------------------------------
-- Initialize the target object to prepare for reading process events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Process_Probe : constant Process_Probe_Type_Access
:= new Process_Probe_Type;
begin
Process_Probe.Target := Target'Unrestricted_Access;
Process_Probe.Events := Manager.Get_Target_Events;
Register (Manager, Process_Probe);
end Initialize;
end MAT.Targets.Probes;
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Targets.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes");
MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0;
MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
M_HEAP_START : constant MAT.Events.Internal_Reference := 3;
M_HEAP_END : constant MAT.Events.Internal_Reference := 4;
M_END : constant MAT.Events.Internal_Reference := 5;
PID_NAME : aliased constant String := "pid";
EXE_NAME : aliased constant String := "exe";
HP_START_NAME : aliased constant String := "hp_start";
HP_END_NAME : aliased constant String := "hp_end";
END_NAME : aliased constant String := "end";
Process_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => PID_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_PID),
2 => (Name => EXE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_EXE),
3 => (Name => HP_START_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START),
4 => (Name => HP_END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END),
5 => (Name => END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_END));
-- ------------------------------
-- Create a new process after the begin event is received from the event stream.
-- ------------------------------
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Probe.Target.Create_Process (Pid => Pid,
Path => Path,
Process => Probe.Target.Current);
Probe.Target.Process.Events := Probe.Events;
MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory,
Manager => Probe.Manager.all);
end Create_Process;
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Addr;
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
Heap : MAT.Memory.Region_Info;
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_PID =>
Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg);
when M_HEAP_START =>
Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when M_HEAP_END =>
Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
Heap.Size := Heap.End_Addr - Heap.Start_Addr;
Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]");
Probe.Create_Process (Pid, Path);
Probe.Manager.Read_Message (Msg);
Probe.Manager.Read_Event_Definitions (Msg);
Probe.Target.Process.Memory.Add_Region (Heap);
end Probe_Begin;
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type) is
use type MAT.Events.Targets.Probe_Index_Type;
begin
if Event.Index = MSG_BEGIN then
Probe.Probe_Begin (Event.Index, Params.all, Msg);
end if;
end Extract;
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
null;
end Execute;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access) is
begin
Probe.Manager := Into'Unchecked_Access;
Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "end", MSG_END,
Process_Attributes'Access);
end Register;
-- ------------------------------
-- Initialize the target object to prepare for reading process events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Process_Probe : constant Process_Probe_Type_Access
:= new Process_Probe_Type;
begin
Process_Probe.Target := Target'Unrestricted_Access;
Process_Probe.Events := Manager.Get_Target_Events;
Register (Manager, Process_Probe);
end Initialize;
end MAT.Targets.Probes;
|
Use Get_Target_Process_Ref function to retrieve the PID
|
Use Get_Target_Process_Ref function to retrieve the PID
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e9fe9e1cc186b926afcc3cd6a7f754d151f01c3f
|
src/util-serialize-mappers.adb
|
src/util-serialize-mappers.adb
|
-----------------------------------------------------------------------
-- util-serialize-mappers -- Serialize objects in various formats
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
package body Util.Serialize.Mappers is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers",
Util.Log.WARN_LEVEL);
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
begin
if Handler.Mapper /= null then
Handler.Mapper.all.Execute (Map, Ctx, Value);
end if;
end Execute;
function Is_Proxy (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Proxy_Mapper;
end Is_Proxy;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
function Find_Mapper (Controller : in Mapper;
Name : in String;
Attribute : in Boolean := False) return Mapper_Access is
use type Ada.Strings.Unbounded.Unbounded_String;
Node : Mapper_Access := Controller.First_Child;
begin
if Node = null and Controller.Mapper /= null then
return Controller.Mapper.Find_Mapper (Name, Attribute);
end if;
while Node /= null loop
if Node.Name = Name then
if (Attribute = False and Node.Mapping = null)
or else not Node.Mapping.Is_Attribute then
return Node;
end if;
if Attribute and Node.Mapping.Is_Attribute then
return Node;
end if;
end if;
Node := Node.Next_Mapping;
end loop;
return null;
end Find_Mapper;
-- -----------------------
-- Find a path component representing a child mapper under <b>From</b> and
-- identified by the given <b>Name</b>. If the mapper is not found, a new
-- Mapper_Node is created.
-- -----------------------
procedure Find_Path_Component (From : in out Mapper'Class;
Name : in String;
Result : out Mapper_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access := From.First_Child;
begin
if Node = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
From.First_Child := Result;
return;
end if;
loop
if Node.Name = Name then
Result := Node;
return;
end if;
if Node.Next_Mapping = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Node.Next_Mapping := Result;
return;
end if;
Node := Node.Next_Mapping;
end loop;
end Find_Path_Component;
-- -----------------------
-- Build the mapping tree that corresponds to the given <b>Path</b>.
-- Each path component is represented by a <b>Mapper_Node</b> element.
-- The node is created if it does not exists.
-- -----------------------
procedure Build_Path (Into : in out Mapper'Class;
Path : in String;
Last_Pos : out Natural;
Node : out Mapper_Access) is
Pos : Natural;
begin
Node := Into'Unchecked_Access;
Last_Pos := Path'First;
loop
Pos := Util.Strings.Index (Source => Path,
Char => '/',
From => Last_Pos);
if Pos = 0 then
Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last),
Result => Node);
Last_Pos := Path'Last + 1;
else
Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1),
Result => Node);
Last_Pos := Pos + 1;
end if;
exit when Last_Pos > Path'Last;
end loop;
end Build_Path;
-- -----------------------
-- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>.
-- The <b>Path</b> string describes the matching node using a simplified XPath notation.
-- Example:
-- info/first_name matches: <info><first_name>...</first_name></info>
-- info/a/b/name matches: <info><a><b><name>...</name></b></a></info>
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapper_Access) is
Node : Mapper_Access;
Last_Pos : Natural;
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access) is
N : Mapper_Access;
Src : Mapper_Access := From;
begin
while Src /= null loop
N := Src.Clone;
N.Is_Clone := True;
N.Next_Mapping := To.First_Child;
To.First_Child := N;
if Src.First_Child /= null then
Copy (N, Src.First_Child);
end if;
Src := Src.Next_Mapping;
end loop;
end Copy;
begin
Log.Info ("Mapping {0} for mapper X", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapper /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
Copy (Node, Map.First_Child);
end Add_Mapping;
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapping_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access;
Last_Pos : Natural;
begin
Log.Info ("Mapping {0}", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapping /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Length (Node.Name) = 0 then
Log.Warn ("Mapped name is empty in mapping path {0}", Path);
elsif Element (Node.Name, 1) = '@' then
Delete (Node.Name, 1, 1);
Map.Is_Attribute := True;
else
Map.Is_Attribute := False;
end if;
Node.Mapping := Map;
Node.Mapper := Into'Unchecked_Access;
end Add_Mapping;
-- -----------------------
-- Clone the <b>Handler</b> instance and get a copy of that single object.
-- -----------------------
function Clone (Handler : in Mapper) return Mapper_Access is
Result : constant Mapper_Access := new Mapper;
begin
Result.Name := Handler.Name;
Result.Mapper := Handler.Mapper;
Result.Mapping := Handler.Mapping;
Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper;
Result.Is_Clone := True;
return Result;
end Clone;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in Mapper;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False;
Context : in out Util.Serialize.Contexts.Context'Class) is
Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute);
begin
if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then
Map.Mapper.all.Execute (Map.Mapping.all, Context, Value);
end if;
end Set_Member;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Start_Object (Context, Name);
end if;
end Start_Object;
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Finish_Object (Context, Name);
end if;
end Finish_Object;
-- -----------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- -----------------------
procedure Dump (Handler : in Mapper'Class;
Log : in Util.Log.Loggers.Logger'Class;
Prefix : in String := "") is
procedure Dump (Map : in Mapper'Class);
-- -----------------------
-- Dump the mapping description
-- -----------------------
procedure Dump (Map : in Mapper'Class) is
begin
if Map.Mapping /= null and then Map.Mapping.Is_Attribute then
Log.Info (" {0}@{1}", Prefix,
Ada.Strings.Unbounded.To_String (Map.Mapping.Name));
else
Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name));
Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name));
end if;
end Dump;
begin
Iterate (Handler, Dump'Access);
end Dump;
procedure Iterate (Controller : in Mapper;
Process : not null access procedure (Map : in Mapper'Class)) is
Node : Mapper_Access := Controller.First_Child;
begin
-- Pass 1: process the attributes first
while Node /= null loop
if Node.Mapping /= null and then Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
-- Pass 2: process the elements
Node := Controller.First_Child;
while Node /= null loop
if Node.Mapping = null or else not Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
end Iterate;
-- -----------------------
-- Finalize the object and release any mapping.
-- -----------------------
overriding
procedure Finalize (Controller : in out Mapper) is
procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access);
procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access);
Node : Mapper_Access := Controller.First_Child;
Next : Mapper_Access;
begin
Controller.First_Child := null;
while Node /= null loop
Next := Node.Next_Mapping;
Free (Node);
Node := Next;
end loop;
if not Controller.Is_Clone then
Free (Controller.Mapping);
else
Controller.Mapping := null;
end if;
end Finalize;
end Util.Serialize.Mappers;
|
-----------------------------------------------------------------------
-- util-serialize-mappers -- Serialize objects in various formats
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
package body Util.Serialize.Mappers is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers",
Util.Log.WARN_LEVEL);
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
begin
if Handler.Mapper /= null then
Handler.Mapper.all.Execute (Map, Ctx, Value);
end if;
end Execute;
function Is_Proxy (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Proxy_Mapper;
end Is_Proxy;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
function Find_Mapper (Controller : in Mapper;
Name : in String;
Attribute : in Boolean := False) return Mapper_Access is
use type Ada.Strings.Unbounded.Unbounded_String;
Node : Mapper_Access := Controller.First_Child;
begin
if Node = null and Controller.Mapper /= null then
return Controller.Mapper.Find_Mapper (Name, Attribute);
end if;
while Node /= null loop
if Node.Name = Name then
if (Attribute = False and Node.Mapping = null)
or else not Node.Mapping.Is_Attribute then
return Node;
end if;
if Attribute and Node.Mapping.Is_Attribute then
return Node;
end if;
end if;
Node := Node.Next_Mapping;
end loop;
return null;
end Find_Mapper;
-- -----------------------
-- Find a path component representing a child mapper under <b>From</b> and
-- identified by the given <b>Name</b>. If the mapper is not found, a new
-- Mapper_Node is created.
-- -----------------------
procedure Find_Path_Component (From : in out Mapper'Class;
Name : in String;
Result : out Mapper_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access := From.First_Child;
begin
if Node = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
From.First_Child := Result;
return;
end if;
loop
if Node.Name = Name then
Result := Node;
return;
end if;
if Node.Next_Mapping = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Node.Next_Mapping := Result;
return;
end if;
Node := Node.Next_Mapping;
end loop;
end Find_Path_Component;
-- -----------------------
-- Build the mapping tree that corresponds to the given <b>Path</b>.
-- Each path component is represented by a <b>Mapper_Node</b> element.
-- The node is created if it does not exists.
-- -----------------------
procedure Build_Path (Into : in out Mapper'Class;
Path : in String;
Last_Pos : out Natural;
Node : out Mapper_Access) is
Pos : Natural;
begin
Node := Into'Unchecked_Access;
Last_Pos := Path'First;
loop
Pos := Util.Strings.Index (Source => Path,
Char => '/',
From => Last_Pos);
if Pos = 0 then
Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last),
Result => Node);
Last_Pos := Path'Last + 1;
else
Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1),
Result => Node);
Last_Pos := Pos + 1;
end if;
exit when Last_Pos > Path'Last;
end loop;
end Build_Path;
-- -----------------------
-- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>.
-- The <b>Path</b> string describes the matching node using a simplified XPath notation.
-- Example:
-- info/first_name matches: <info><first_name>...</first_name></info>
-- info/a/b/name matches: <info><a><b><name>...</name></b></a></info>
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapper_Access) is
Node : Mapper_Access;
Last_Pos : Natural;
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access) is
N : Mapper_Access;
Src : Mapper_Access := From;
begin
while Src /= null loop
N := Src.Clone;
N.Is_Clone := True;
N.Next_Mapping := To.First_Child;
To.First_Child := N;
if Src.First_Child /= null then
Copy (N, Src.First_Child);
end if;
Src := Src.Next_Mapping;
end loop;
end Copy;
begin
Log.Info ("Mapping {0} for mapper X", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapper /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Map.First_Child /= null then
Copy (Node, Map.First_Child);
else
Node.Mapper := Map;
end if;
end Add_Mapping;
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapping_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access;
Last_Pos : Natural;
begin
Log.Info ("Mapping {0}", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapping /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Length (Node.Name) = 0 then
Log.Warn ("Mapped name is empty in mapping path {0}", Path);
elsif Element (Node.Name, 1) = '@' then
Delete (Node.Name, 1, 1);
Map.Is_Attribute := True;
else
Map.Is_Attribute := False;
end if;
Node.Mapping := Map;
Node.Mapper := Into'Unchecked_Access;
end Add_Mapping;
-- -----------------------
-- Clone the <b>Handler</b> instance and get a copy of that single object.
-- -----------------------
function Clone (Handler : in Mapper) return Mapper_Access is
Result : constant Mapper_Access := new Mapper;
begin
Result.Name := Handler.Name;
Result.Mapper := Handler.Mapper;
Result.Mapping := Handler.Mapping;
Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper;
Result.Is_Clone := True;
return Result;
end Clone;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in Mapper;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False;
Context : in out Util.Serialize.Contexts.Context'Class) is
Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute);
begin
if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then
Map.Mapper.all.Execute (Map.Mapping.all, Context, Value);
end if;
end Set_Member;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Start_Object (Context, Name);
end if;
end Start_Object;
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Finish_Object (Context, Name);
end if;
end Finish_Object;
-- -----------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- -----------------------
procedure Dump (Handler : in Mapper'Class;
Log : in Util.Log.Loggers.Logger'Class;
Prefix : in String := "") is
procedure Dump (Map : in Mapper'Class);
-- -----------------------
-- Dump the mapping description
-- -----------------------
procedure Dump (Map : in Mapper'Class) is
begin
if Map.Mapping /= null and then Map.Mapping.Is_Attribute then
Log.Info (" {0}@{1}", Prefix,
Ada.Strings.Unbounded.To_String (Map.Mapping.Name));
else
Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name));
Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name));
end if;
end Dump;
begin
Iterate (Handler, Dump'Access);
end Dump;
procedure Iterate (Controller : in Mapper;
Process : not null access procedure (Map : in Mapper'Class)) is
Node : Mapper_Access := Controller.First_Child;
begin
-- Pass 1: process the attributes first
while Node /= null loop
if Node.Mapping /= null and then Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
-- Pass 2: process the elements
Node := Controller.First_Child;
while Node /= null loop
if Node.Mapping = null or else not Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
end Iterate;
-- -----------------------
-- Finalize the object and release any mapping.
-- -----------------------
overriding
procedure Finalize (Controller : in out Mapper) is
procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access);
procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access);
Node : Mapper_Access := Controller.First_Child;
Next : Mapper_Access;
begin
Controller.First_Child := null;
while Node /= null loop
Next := Node.Next_Mapping;
Free (Node);
Node := Next;
end loop;
if not Controller.Is_Clone then
Free (Controller.Mapping);
else
Controller.Mapping := null;
end if;
end Finalize;
end Util.Serialize.Mappers;
|
Fix serialization mapping for vectors - when adding a vector mapping, do not copy the mapping but set the mapper to the vector mapping
|
Fix serialization mapping for vectors
- when adding a vector mapping, do not copy the mapping
but set the mapper to the vector mapping
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
a9a6569cd4935a7ae2f45a74524d5b2f51040e4f
|
src/wiki-filters-variables.adb
|
src/wiki-filters-variables.adb
|
-----------------------------------------------------------------------
-- wiki-filters-variables -- Expand variables in text and links
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Variables is
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is
begin
return Wiki.Strings.Index (Text, "$") > 0;
end Need_Expand;
procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Add_Variable (Name, Value);
return;
end if;
Filter := Filter.Next;
end loop;
end Add_Variable;
-- ------------------------------
-- Add a variable to replace the given name by its value.
-- ------------------------------
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Name, Value);
end Add_Variable;
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in String;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value);
end Add_Variable;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Need_Expand (Header) then
Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level);
else
Filter_Type (Filter).Add_Header (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Add a text content with the given format to the document. Replace variables
-- that are contained in the text.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Need_Expand (Text) then
Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format);
else
Filter_Type (Filter).Add_Text (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Expand the variables contained in the text.
-- ------------------------------
function Expand (Filter : in Variable_Filter;
Text : in Wiki.Strings.WString) return Wiki.Strings.WString is
First : Natural := Text'First;
Pos : Natural;
Last : Natural;
Name_Start : Natural;
Name_End : Natural;
Result : Wiki.Strings.BString (256);
Item : Variable_Cursor;
Match_End : Wiki.Strings.WChar;
begin
while First <= Text'Last loop
Pos := First;
while Pos <= Text'Last and then Text (Pos) /= '$' loop
Pos := Pos + 1;
end loop;
exit when Pos >= Text'Last;
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1));
First := Pos;
Name_Start := Pos + 1;
if Text (Name_Start) = '(' or Text (Name_Start) = '{' then
Match_End := (if Text (Name_Start) = '(' then ')' else '}');
Name_Start := Name_Start + 1;
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop
Name_End := Name_End + 1;
end loop;
exit when Name_End > Text'Last;
exit when Text (Name_End) /= Match_End;
Last := Name_End + 1;
Name_End := Name_End - 1;
else
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop
Name_End := Name_End + 1;
end loop;
Last := Name_End;
Name_End := Name_End - 1;
end if;
Item := Filter.Variables.Find (Text (Name_Start .. Name_End));
if Variable_Maps.Has_Element (Item) then
Strings.Wide_Wide_Builders.Append (Result, Variable_Maps.Element (Item));
elsif Last > Text'Last then
exit;
else
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last));
end if;
First := Last;
end loop;
if First <= Text'Last then
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last));
end if;
return Strings.Wide_Wide_Builders.To_Array (Result);
end Expand;
end Wiki.Filters.Variables;
|
-----------------------------------------------------------------------
-- wiki-filters-variables -- Expand variables in text and links
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Variables is
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean;
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is
begin
return Wiki.Strings.Index (Text, "$") > 0;
end Need_Expand;
procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Add_Variable (Name, Value);
return;
end if;
Filter := Filter.Next;
end loop;
end Add_Variable;
-- ------------------------------
-- Add a variable to replace the given name by its value.
-- ------------------------------
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Name, Value);
end Add_Variable;
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in String;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value);
end Add_Variable;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Need_Expand (Header) then
Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level);
else
Filter_Type (Filter).Add_Header (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Add a text content with the given format to the document. Replace variables
-- that are contained in the text.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Need_Expand (Text) then
Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format);
else
Filter_Type (Filter).Add_Text (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Expand the variables contained in the text.
-- ------------------------------
function Expand (Filter : in Variable_Filter;
Text : in Wiki.Strings.WString) return Wiki.Strings.WString is
First : Natural := Text'First;
Pos : Natural;
Last : Natural;
Name_Start : Natural;
Name_End : Natural;
Result : Wiki.Strings.BString (256);
Item : Variable_Cursor;
Match_End : Wiki.Strings.WChar;
begin
while First <= Text'Last loop
Pos := First;
while Pos <= Text'Last and then Text (Pos) /= '$' loop
Pos := Pos + 1;
end loop;
exit when Pos >= Text'Last;
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1));
First := Pos;
Name_Start := Pos + 1;
if Text (Name_Start) = '(' or Text (Name_Start) = '{' then
Match_End := (if Text (Name_Start) = '(' then ')' else '}');
Name_Start := Name_Start + 1;
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop
Name_End := Name_End + 1;
end loop;
exit when Name_End > Text'Last;
exit when Text (Name_End) /= Match_End;
Last := Name_End + 1;
Name_End := Name_End - 1;
else
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop
Name_End := Name_End + 1;
end loop;
Last := Name_End;
Name_End := Name_End - 1;
end if;
Item := Filter.Variables.Find (Text (Name_Start .. Name_End));
if Variable_Maps.Has_Element (Item) then
Strings.Wide_Wide_Builders.Append (Result, Variable_Maps.Element (Item));
elsif Last > Text'Last then
exit;
else
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last));
end if;
First := Last;
end loop;
if First <= Text'Last then
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last));
end if;
return Strings.Wide_Wide_Builders.To_Array (Result);
end Expand;
-- ------------------------------
-- Iterate over the filter variables.
-- ------------------------------
procedure Iterate (Filter : in Variable_Filter;
Process : not null
access procedure (Name, Value : in Strings.WString)) is
Iter : Variable_Cursor := Filter.Variables.First;
begin
while Variable_Maps.Has_Element (Iter) loop
Variable_Maps.Query_Element (Iter, Process);
Variable_Maps.Next (Iter);
end loop;
end Iterate;
end Wiki.Filters.Variables;
|
Implement the Iterate procedure to iterate over the filter variables
|
Implement the Iterate procedure to iterate over the filter variables
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1c6c3604877d9152c8a6f42ed48a2e0afaea0730
|
src/wiki-filters-variables.adb
|
src/wiki-filters-variables.adb
|
-----------------------------------------------------------------------
-- wiki-filters-variables -- Expand variables in text and links
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Variables is
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean;
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is
begin
return Wiki.Strings.Index (Text, "$") > 0;
end Need_Expand;
procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Add_Variable (Name, Value);
return;
end if;
Filter := Filter.Next;
end loop;
end Add_Variable;
-- ------------------------------
-- Add a variable to replace the given name by its value.
-- ------------------------------
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Name, Value);
end Add_Variable;
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in String;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value);
end Add_Variable;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Need_Expand (Header) then
Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level);
else
Filter_Type (Filter).Add_Header (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Add a text content with the given format to the document. Replace variables
-- that are contained in the text.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Need_Expand (Text) then
Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format);
else
Filter_Type (Filter).Add_Text (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Expand the variables contained in the text.
-- ------------------------------
function Expand (Filter : in Variable_Filter;
Text : in Wiki.Strings.WString) return Wiki.Strings.WString is
First : Natural := Text'First;
Pos : Natural;
Last : Natural;
Name_Start : Natural;
Name_End : Natural;
Result : Wiki.Strings.BString (256);
Item : Variable_Cursor;
Match_End : Wiki.Strings.WChar;
begin
while First <= Text'Last loop
Pos := First;
while Pos <= Text'Last and then Text (Pos) /= '$' loop
Pos := Pos + 1;
end loop;
exit when Pos >= Text'Last;
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1));
First := Pos;
Name_Start := Pos + 1;
if Text (Name_Start) = '(' or Text (Name_Start) = '{' then
Match_End := (if Text (Name_Start) = '(' then ')' else '}');
Name_Start := Name_Start + 1;
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop
Name_End := Name_End + 1;
end loop;
exit when Name_End > Text'Last;
exit when Text (Name_End) /= Match_End;
Last := Name_End + 1;
Name_End := Name_End - 1;
else
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop
Name_End := Name_End + 1;
end loop;
Last := Name_End;
Name_End := Name_End - 1;
end if;
Item := Filter.Variables.Find (Text (Name_Start .. Name_End));
if Variable_Maps.Has_Element (Item) then
Strings.Wide_Wide_Builders.Append (Result, Variable_Maps.Element (Item));
elsif Last > Text'Last then
exit;
else
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last));
end if;
First := Last;
end loop;
if First <= Text'Last then
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last));
end if;
return Strings.Wide_Wide_Builders.To_Array (Result);
end Expand;
-- ------------------------------
-- Iterate over the filter variables.
-- ------------------------------
procedure Iterate (Filter : in Variable_Filter;
Process : not null
access procedure (Name, Value : in Strings.WString)) is
Iter : Variable_Cursor := Filter.Variables.First;
begin
while Variable_Maps.Has_Element (Iter) loop
Variable_Maps.Query_Element (Iter, Process);
Variable_Maps.Next (Iter);
end loop;
end Iterate;
procedure Iterate (Chain : in Wiki.Filters.Filter_Chain;
Process : not null
access procedure (Name, Value : in Strings.WString)) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Iterate (Process);
return;
end if;
Filter := Filter.Next;
end loop;
end Iterate;
end Wiki.Filters.Variables;
|
-----------------------------------------------------------------------
-- wiki-filters-variables -- Expand variables in text and links
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Variables is
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean;
function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is
begin
return Wiki.Strings.Index (Text, "$") > 0;
end Need_Expand;
procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Add_Variable (Name, Value);
return;
end if;
Filter := Filter.Next;
end loop;
end Add_Variable;
-- ------------------------------
-- Add a variable to replace the given name by its value.
-- ------------------------------
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Name, Value);
end Add_Variable;
procedure Add_Variable (Filter : in out Variable_Filter;
Name : in String;
Value : in Wiki.Strings.WString) is
begin
Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value);
end Add_Variable;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Need_Expand (Header) then
Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level);
else
Filter_Type (Filter).Add_Header (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Add a text content with the given format to the document. Replace variables
-- that are contained in the text.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Need_Expand (Text) then
Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format);
else
Filter_Type (Filter).Add_Text (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Filter : in out Variable_Filter;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Need_Expand (Name) then
Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes);
else
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Expand the variables contained in the text.
-- ------------------------------
function Expand (Filter : in Variable_Filter;
Text : in Wiki.Strings.WString) return Wiki.Strings.WString is
First : Natural := Text'First;
Pos : Natural;
Last : Natural;
Name_Start : Natural;
Name_End : Natural;
Result : Wiki.Strings.BString (256);
Item : Variable_Cursor;
Match_End : Wiki.Strings.WChar;
begin
while First <= Text'Last loop
Pos := First;
while Pos <= Text'Last and then Text (Pos) /= '$' loop
Pos := Pos + 1;
end loop;
exit when Pos >= Text'Last;
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1));
First := Pos;
Name_Start := Pos + 1;
if Text (Name_Start) = '(' or Text (Name_Start) = '{' then
Match_End := (if Text (Name_Start) = '(' then ')' else '}');
Name_Start := Name_Start + 1;
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop
Name_End := Name_End + 1;
end loop;
exit when Name_End > Text'Last;
exit when Text (Name_End) /= Match_End;
Last := Name_End + 1;
Name_End := Name_End - 1;
else
Name_End := Name_Start;
while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop
Name_End := Name_End + 1;
end loop;
Last := Name_End;
Name_End := Name_End - 1;
end if;
Item := Filter.Variables.Find (Text (Name_Start .. Name_End));
if Variable_Maps.Has_Element (Item) then
Strings.Wide_Wide_Builders.Append (Result, Variable_Maps.Element (Item));
First := Last;
elsif Last > Text'Last then
exit;
else
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last));
First := Last + 1;
end if;
end loop;
if First <= Text'Last then
Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last));
end if;
return Strings.Wide_Wide_Builders.To_Array (Result);
end Expand;
-- ------------------------------
-- Iterate over the filter variables.
-- ------------------------------
procedure Iterate (Filter : in Variable_Filter;
Process : not null
access procedure (Name, Value : in Strings.WString)) is
Iter : Variable_Cursor := Filter.Variables.First;
begin
while Variable_Maps.Has_Element (Iter) loop
Variable_Maps.Query_Element (Iter, Process);
Variable_Maps.Next (Iter);
end loop;
end Iterate;
procedure Iterate (Chain : in Wiki.Filters.Filter_Chain;
Process : not null
access procedure (Name, Value : in Strings.WString)) is
Filter : Filter_Type_Access := Chain.Next;
begin
while Filter /= null loop
if Filter.all in Variable_Filter'Class then
Variable_Filter'Class (Filter.all).Iterate (Process);
return;
end if;
Filter := Filter.Next;
end loop;
end Iterate;
end Wiki.Filters.Variables;
|
Fix replacing a variable at end of the string
|
Fix replacing a variable at end of the string
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
4138f26764a99cae27c7c43be0c98a07161b2b88
|
src/wiki-plugins-templates.ads
|
src/wiki-plugins-templates.ads
|
-----------------------------------------------------------------------
-- 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.Strings;
-- === Template Plugins ===
-- The <b>Wiki.Plugins.Templates</b> package defines an abstract template plugin.
-- To use the template plugin, the <tt>Get_Template</tt> procedure must be implemented.
-- It is responsible for getting the template content according to the plugin parameters.
--
package Wiki.Plugins.Templates is
pragma Preelaborate;
type Template_Plugin is abstract new Wiki_Plugin with null record;
-- Get the template content for the plugin evaluation.
procedure Get_Template (Plugin : in out Template_Plugin;
Params : in out Wiki.Attributes.Attribute_List;
Template : out Wiki.Strings.UString) is abstract;
-- 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);
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.Strings.Unbounded;
with Wiki.Strings;
-- === Template Plugins ===
-- The <b>Wiki.Plugins.Templates</b> package defines an abstract template plugin.
-- To use the template plugin, the <tt>Get_Template</tt> procedure must be implemented.
-- It is responsible for getting the template content according to the plugin parameters.
--
package Wiki.Plugins.Templates is
type Template_Plugin is abstract new Wiki_Plugin with null record;
-- Get the template content for the plugin evaluation.
procedure Get_Template (Plugin : in out Template_Plugin;
Params : in out Wiki.Attributes.Attribute_List;
Template : out Wiki.Strings.UString) is abstract;
-- 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);
type File_Template_Plugin is new Wiki_Plugin with private;
-- Set the directory path that contains template files.
procedure Set_Template_Path (Plugin : in out File_Template_Plugin;
Path : in String);
-- 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);
private
type File_Template_Plugin is new Wiki_Plugin with record
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Wiki.Plugins.Templates;
|
Declare the File_Template_Plugin type for the template evaluation based on a file read from a directory
|
Declare the File_Template_Plugin type for the template evaluation
based on a file read from a directory
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
00cbe4f543812e68f58fdc333b96db2992ac4e66
|
ARM/STM32/driver_demos/demo_gpio_blinky/src/demo_gpio_blinky.adb
|
ARM/STM32/driver_demos/demo_gpio_blinky/src/demo_gpio_blinky.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- A simple example that blinks all the LEDs simultaneously, w/o tasking.
-- It does not use the various convenience functions defined elsewhere, but
-- instead works directly with the GPIO driver to configure and control the
-- LEDs.
-- Note that this code is independent of the specific MCU device and board
-- in use because we use names and constants that are common across all of
-- them. For example, "All_LEDs" refers to different GPIO pins on different
-- boards, and indeed defines a different number of LEDs on different boards.
-- The gpr file determines which board is actually used.
with STM32.Device; use STM32.Device;
with STM32.Board; use STM32.Board;
with STM32.GPIO; use STM32.GPIO;
with Ada.Real_Time; use Ada.Real_Time;
procedure Demo_GPIO_Blinky is
use STM32;
Period : constant Time_Span := Milliseconds (250);
Next : Time := Clock;
procedure Initialize_LEDs;
-- Configures the GPIO pins and port connected to the LEDs on the board
-- in use so that we can drive them via GPIO commands. Note that the board
-- package provides a procedure to do this directly, for convenience, but
-- we do not use it here for the sake of illustration.
procedure Initialize_LEDs is
Configuration : GPIO_Port_Configuration;
begin
Enable_Clock (All_LEDs);
Configuration.Mode := Mode_Out;
Configuration.Output_Type := Push_Pull;
Configuration.Speed := Speed_100MHz;
Configuration.Resistors := Floating;
Configure_IO (All_LEDs, Configuration);
end Initialize_LEDs;
begin
Initialize_LEDs;
loop
Toggle (All_LEDs);
Next := Next + Period;
delay until Next;
end loop;
end Demo_GPIO_Blinky;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- A simple example that blinks all the LEDs simultaneously, w/o tasking.
-- It does not use the various convenience functions defined elsewhere, but
-- instead works directly with the GPIO driver to configure and control the
-- LEDs.
-- Note that this code is independent of the specific MCU device and board
-- in use because we use names and constants that are common across all of
-- them. For example, "All_LEDs" refers to different GPIO pins on different
-- boards, and indeed defines a different number of LEDs on different boards.
-- The gpr file determines which board is actually used.
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
-- The "last chance handler" is the user-defined routine that is called when
-- an exception is propagated. We need it in the executable, therefore it
-- must be somewhere in the closure of the context clauses.
with STM32.Device; use STM32.Device;
with STM32.Board; use STM32.Board;
with STM32.GPIO; use STM32.GPIO;
with Ada.Real_Time; use Ada.Real_Time;
procedure Demo_GPIO_Blinky is
use STM32;
Period : constant Time_Span := Milliseconds (250);
Next : Time := Clock;
procedure Initialize_LEDs;
-- Configures the GPIO pins and port connected to the LEDs on the board
-- in use so that we can drive them via GPIO commands. Note that the board
-- package provides a procedure to do this directly, for convenience, but
-- we do not use it here for the sake of illustration.
procedure Initialize_LEDs is
Configuration : GPIO_Port_Configuration;
begin
Enable_Clock (All_LEDs);
Configuration.Mode := Mode_Out;
Configuration.Output_Type := Push_Pull;
Configuration.Speed := Speed_100MHz;
Configuration.Resistors := Floating;
Configure_IO (All_LEDs, Configuration);
end Initialize_LEDs;
begin
Initialize_LEDs;
loop
Toggle (All_LEDs);
Next := Next + Period;
delay until Next;
end loop;
end Demo_GPIO_Blinky;
|
Include LCH overriding default.
|
Include LCH overriding default.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library
|
73124709026490ce615128858d97b2e34a132b74
|
src/util-dates.adb
|
src/util-dates.adb
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013, 2014, 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 Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of).
-- ------------------------------
function Time_Of (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => Date.Hour,
Minute => Date.Minute,
Second => Date.Second,
Sub_Second => Date.Sub_Second,
Time_Zone => Date.Time_Zone);
end Time_Of;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 365;
else
return 366;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013, 2014, 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 Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of).
-- ------------------------------
function Time_Of (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => Date.Hour,
Minute => Date.Minute,
Second => Date.Second,
Sub_Second => Date.Sub_Second,
Time_Zone => Date.Time_Zone);
end Time_Of;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Returns true if both dates are on the same day.
-- ------------------------------
function Is_Same_Day (Date1, Date2 : in Ada.Calendar.Time) return Boolean is
Split_Date1 : Date_Record;
Split_Date2 : Date_Record;
begin
Split (Split_Date1, Date1);
Split (Split_Date2, Date2);
return Is_Same_Day (Split_Date1, Split_Date2);
end Is_Same_Day;
function Is_Same_Day (Date1, Date2 : in Date_Record) return Boolean is
begin
return Date1.Year = Date2.Year
and Date1.Month = Date2.Month
and Date1.Month_Day = Date2.Month_Day;
end Is_Same_Day;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 365;
else
return 366;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
Implement the Is_Same_Day function
|
Implement the Is_Same_Day function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0172066751fd97383010bda942c06ae82adb1865
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link : Wiki.Attributes.Attribute_List_Type;
when N_QUOTE =>
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
type Node_Type_Access is access all Node_Type;
type Document_Node_Access is private;
type Document is limited private;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
type Node_List is limited record
N : Natural;
end record;
type Document_Node;
type Document_Node_Access is access all Document_Node;
type Document_Node (Kind : Node_Kind; Len : Natural) is limited record
Next : Document_Node_Access;
Prev : Document_Node_Access;
Data : Node_Type (Kind, Len);
end record;
type Document is limited record
First : Document_Node_Access;
Last : Document_Node_Access;
end record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link : Wiki.Attributes.Attribute_List_Type;
when N_QUOTE =>
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
type Node_Type_Access is access all Node_Type;
type Document_Node_Access is private;
type Document is limited private;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
type Document_Node;
type Document_Node_Access is access all Document_Node;
type Document_Node (Kind : Node_Kind; Len : Natural) is limited record
Next : Document_Node_Access;
Prev : Document_Node_Access;
Data : Node_Type (Kind, Len);
end record;
type Document is limited record
First : Document_Node_Access;
Last : Document_Node_Access;
end record;
end Wiki.Nodes;
|
Declare Node_List_Block and Node_List types
|
Declare Node_List_Block and Node_List types
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a5b5f0b24ea036a6da53ba9019160ab8731a6aa4
|
src/asf-components-html.adb
|
src/asf-components-html.adb
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- 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.Objects;
with Util.Strings;
package body ASF.Components.Html is
use EL.Objects;
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
TABINDEX_ATTR : aliased constant String := "tabindex";
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Writer : in ResponseWriter_Access) is
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
begin
Writer.Write_Attribute ("id", UI.Get_Client_Id);
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
end if;
if not Is_Null (Style) then
Writer.Write_Attribute ("style", Style);
end if;
if not Is_Null (Title) then
Writer.Write_Attribute ("title", Title);
end if;
end Render_Attributes;
-- ------------------------------
-- Render the attributes which are defined on the component and which are
-- in the list specified by <b>names</b>.
-- ------------------------------
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Names : in Util.Strings.String_Set.Set;
Writer : in ResponseWriter_Access) is
procedure Process_Attribute (Name : in String;
Attr : in UIAttribute) is
begin
if Names.Contains (Name'Unrestricted_Access) then
declare
Value : constant Object := Get_Value (Attr, UI);
begin
if Name = "styleClass" then
Writer.Write_Attribute ("class", Value);
else
Writer.Write_Attribute (Name, Value);
end if;
end;
end if;
end Process_Attribute;
procedure Write_Attributes is new Iterate_Attributes (Process_Attribute);
Id : constant Unbounded_String := UI.Get_Client_Id;
begin
if Length (Id) > 0 then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
Write_Attributes (UI);
end Render_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
end Set_Interactive_Attributes;
end ASF.Components.Html;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- 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.Objects;
package body ASF.Components.Html is
use EL.Objects;
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
TABINDEX_ATTR : aliased constant String := "tabindex";
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Writer : in ResponseWriter_Access) is
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
begin
Writer.Write_Attribute ("id", UI.Get_Client_Id);
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
end if;
if not Is_Null (Style) then
Writer.Write_Attribute ("style", Style);
end if;
if not Is_Null (Title) then
Writer.Write_Attribute ("title", Title);
end if;
end Render_Attributes;
-- ------------------------------
-- Render the attributes which are defined on the component and which are
-- in the list specified by <b>names</b>.
-- ------------------------------
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Names : in Util.Strings.String_Set.Set;
Writer : in ResponseWriter_Access) is
procedure Process_Attribute (Name : in String;
Attr : in UIAttribute) is
begin
if Names.Contains (Name'Unrestricted_Access) then
declare
Value : constant Object := Get_Value (Attr, UI);
begin
if Name = "styleClass" then
Writer.Write_Attribute ("class", Value);
else
Writer.Write_Attribute (Name, Value);
end if;
end;
end if;
end Process_Attribute;
procedure Write_Attributes is new Iterate_Attributes (Process_Attribute);
Id : constant Unbounded_String := UI.Get_Client_Id;
begin
if Length (Id) > 0 then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
Write_Attributes (UI);
end Render_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
Names.Insert (ON_BLUR_ATTR'Access);
Names.Insert (ON_MOUSE_UP_ATTR'Access);
Names.Insert (ON_MOUSE_OVER_ATTR'Access);
Names.Insert (ON_MOUSE_OUT_ATTR'Access);
Names.Insert (ON_MOUSE_MOVE_ATTR'Access);
Names.Insert (ON_MOUSE_DOWN_ATTR'Access);
Names.Insert (ON_KEYUP_ATTR'Access);
Names.Insert (ON_KEYDOWN_ATTR'Access);
Names.Insert (ON_FOCUS_ATTR'Access);
Names.Insert (ON_DBLCLICK_ATTR'Access);
Names.Insert (ON_CLICK_ATTR'Access);
end Set_Interactive_Attributes;
end ASF.Components.Html;
|
Update the definition of interative attributes.
|
Update the definition of interative attributes.
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
ccdefd809b10c8a1af8e792b350b38ebcc973040
|
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.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] [-d 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 ("-d 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: d:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'e' =>
Target.Options.Print_Events := True;
when 'b' =>
Target.Options.Server_Mode := True;
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 'd' =>
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 ("mat>");
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
if Target.Options.Server_Mode then
Target.Server.Start (Target'Unchecked_Access, Target.Options.Address);
end if;
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
if Target.Options.Server_Mode then
Target.Server.Stop;
end if;
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] [-s] [-b [ip:]port] [-d 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 ("-s Start the TCP/IP server to receive events");
Put_Line ("-b [ip:]port Define the port and local address to bind");
Put_Line ("-ns Disable the automatic symbols loading");
Put_Line ("-d 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 s nw ns b: d:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'e' =>
Target.Options.Print_Events := True;
when 's' =>
Target.Options.Server_Mode := True;
when 'b' =>
Target.Options.Server_Mode := True;
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 'd' =>
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 ("mat>");
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
if Target.Options.Server_Mode then
Target.Server.Start (Target'Unchecked_Access, Target.Options.Address);
end if;
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
if Target.Options.Server_Mode then
Target.Server.Stop;
end if;
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;
|
Add the -s option to start the TCP/IP server
|
Add the -s option to start the TCP/IP server
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
703ee51dcf59212fb0b1babd88bde469531e86e2
|
src/natools-s_expressions-atom_buffers.adb
|
src/natools-s_expressions-atom_buffers.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Atom_Buffers is
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is
Old_Size, New_Size : Count := 0;
begin
if Buffer.Used + Length <= Buffer.Available then
return;
end if;
Old_Size := Buffer.Available;
New_Size := Buffer.Used + Length;
if Buffer.Ref.Is_Empty then
declare
function Create return Atom;
function Create return Atom is
begin
return Atom'(1 .. New_Size => <>);
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
else
declare
function Create return Atom;
Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query;
function Create return Atom is
begin
return Result : Atom (1 .. New_Size) do
Result (1 .. Old_Size) := Old_Accessor.Data.all;
end return;
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
end if;
Buffer.Available := New_Size;
end Preallocate;
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is
begin
if Data'Length > 0 then
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update.Data.all
(Buffer.Used + 1 .. Buffer.Used + Data'Length)
:= Data;
Buffer.Used := Buffer.Used + Data'Length;
end if;
end Append;
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is
begin
Preallocate (Buffer, 1);
Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data;
Buffer.Used := Buffer.Used + 1;
end Append;
procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom) is
procedure Process (Target : in out Atom);
procedure Process (Target : in out Atom) is
begin
for I in reverse Data'Range loop
Buffer.Used := Buffer.Used + 1;
Target (Buffer.Used) := Data (I);
end loop;
end Process;
begin
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update (Process'Access);
end Append_Reverse;
procedure Invert (Buffer : in out Atom_Buffer) is
procedure Process (Data : in out Atom);
procedure Process (Data : in out Atom) is
Low : Count := Data'First;
High : Count := Buffer.Used;
Tmp : Octet;
begin
while Low < High loop
Tmp := Data (Low);
Data (Low) := Data (High);
Data (High) := Tmp;
Low := Low + 1;
High := High - 1;
end loop;
end Process;
begin
if not Buffer.Ref.Is_Empty then
Buffer.Ref.Update (Process'Access);
end if;
end Invert;
function Length (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Used;
end Length;
function Capacity (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Available;
end Capacity;
function Data (Buffer : Atom_Buffer) return Atom is
begin
if Buffer.Ref.Is_Empty then
pragma Assert (Buffer.Available = 0 and Buffer.Used = 0);
return Null_Atom;
else
return Buffer.Ref.Query.Data.all (1 .. Buffer.Used);
end if;
end Data;
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is
function Create return Atom;
function Create return Atom is
begin
return Null_Atom;
end Create;
begin
if Buffer.Ref.Is_Empty then
declare
Tmp_Ref : constant Atom_Refs.Reference
:= Atom_Refs.Create (Create'Access);
begin
return Tmp_Ref.Query;
end;
else
return Buffer.Ref.Query;
end if;
end Raw_Query;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom)) is
begin
if Buffer.Ref.Is_Empty then
Process.all (Null_Atom);
else
Process.all (Buffer.Ref.Query.Data.all (1 .. Buffer.Used));
end if;
end Query;
procedure Peek
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count)
is
Transmit : constant Count := Count'Min (Data'Length, Buffer.Used);
begin
Length := Buffer.Used;
if Buffer.Ref.Is_Empty then
pragma Assert (Length = 0);
null;
else
Data (Data'First .. Data'First + Transmit - 1)
:= Buffer.Ref.Query.Data.all (1 .. Transmit);
end if;
end Peek;
function Element (Buffer : Atom_Buffer; Position : Count) return Octet is
begin
return Buffer.Ref.Query.Data.all (Position);
end Element;
procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet) is
begin
Data := Buffer.Ref.Query.Data.all (Buffer.Used);
Buffer.Used := Buffer.Used - 1;
end Pop;
procedure Hard_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Ref.Reset;
Buffer.Available := 0;
Buffer.Used := 0;
end Hard_Reset;
procedure Soft_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Used := 0;
end Soft_Reset;
overriding procedure Write
(Buffer : in out Atom_Buffer;
Item : in Ada.Streams.Stream_Element_Array)
renames Append;
overriding procedure Read
(Buffer : in out Atom_Buffer;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Item'Length < Buffer.Used then
Last := Item'Last;
Item := Buffer.Ref.Query.Data.all (1 .. Item'Length);
Buffer.Used := Buffer.Used - Item'Length;
else
Last := Item'First + Buffer.Used - 1;
Item (Item'First .. Last)
:= Buffer.Ref.Query.Data.all (1 .. Buffer.Used);
Buffer.Used := 0;
end if;
end Read;
end Natools.S_Expressions.Atom_Buffers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Atom_Buffers is
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is
Old_Size, New_Size : Count := 0;
begin
if Buffer.Used + Length <= Buffer.Available then
return;
end if;
Old_Size := Buffer.Available;
New_Size := Buffer.Used + Length;
if Buffer.Ref.Is_Empty then
declare
function Create return Atom;
function Create return Atom is
begin
return Atom'(1 .. New_Size => <>);
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
else
declare
function Create return Atom;
Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query;
function Create return Atom is
begin
return Result : Atom (1 .. New_Size) do
Result (1 .. Old_Size) := Old_Accessor.Data.all;
end return;
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
end if;
Buffer.Available := New_Size;
end Preallocate;
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is
begin
if Data'Length > 0 then
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update.Data.all
(Buffer.Used + 1 .. Buffer.Used + Data'Length)
:= Data;
Buffer.Used := Buffer.Used + Data'Length;
end if;
end Append;
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is
begin
Preallocate (Buffer, 1);
Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data;
Buffer.Used := Buffer.Used + 1;
end Append;
procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom) is
procedure Process (Target : in out Atom);
procedure Process (Target : in out Atom) is
begin
for I in reverse Data'Range loop
Buffer.Used := Buffer.Used + 1;
Target (Buffer.Used) := Data (I);
end loop;
end Process;
begin
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update (Process'Access);
end Append_Reverse;
procedure Invert (Buffer : in out Atom_Buffer) is
procedure Process (Data : in out Atom);
procedure Process (Data : in out Atom) is
Low : Count := Data'First;
High : Count := Buffer.Used;
Tmp : Octet;
begin
while Low < High loop
Tmp := Data (Low);
Data (Low) := Data (High);
Data (High) := Tmp;
Low := Low + 1;
High := High - 1;
end loop;
end Process;
begin
if not Buffer.Ref.Is_Empty then
Buffer.Ref.Update (Process'Access);
end if;
end Invert;
function Length (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Used;
end Length;
function Capacity (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Available;
end Capacity;
function Data (Buffer : Atom_Buffer) return Atom is
begin
if Buffer.Ref.Is_Empty then
pragma Assert (Buffer.Available = 0 and Buffer.Used = 0);
return Null_Atom;
else
return Buffer.Ref.Query.Data.all (1 .. Buffer.Used);
end if;
end Data;
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is
function Create return Atom;
function Create return Atom is
begin
return Null_Atom;
end Create;
begin
if Buffer.Ref.Is_Empty then
declare
Tmp_Ref : constant Atom_Refs.Reference
:= Atom_Refs.Create (Create'Access);
begin
return Tmp_Ref.Query;
end;
else
return Buffer.Ref.Query;
end if;
end Raw_Query;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom)) is
begin
if Buffer.Ref.Is_Empty then
Process.all (Null_Atom);
else
Process.all (Buffer.Ref.Query.Data.all (1 .. Buffer.Used));
end if;
end Query;
procedure Peek
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count)
is
Transmit : constant Count := Count'Min (Data'Length, Buffer.Used);
begin
Length := Buffer.Used;
if Buffer.Ref.Is_Empty then
pragma Assert (Length = 0);
null;
else
Data (Data'First .. Data'First + Transmit - 1)
:= Buffer.Ref.Query.Data.all (1 .. Transmit);
end if;
end Peek;
function Element (Buffer : Atom_Buffer; Position : Count) return Octet is
begin
return Buffer.Ref.Query.Data.all (Position);
end Element;
procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet) is
begin
Data := Buffer.Ref.Query.Data.all (Buffer.Used);
Buffer.Used := Buffer.Used - 1;
end Pop;
procedure Hard_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Ref.Reset;
Buffer.Available := 0;
Buffer.Used := 0;
end Hard_Reset;
procedure Soft_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Used := 0;
end Soft_Reset;
overriding procedure Write
(Buffer : in out Atom_Buffer;
Item : in Ada.Streams.Stream_Element_Array)
renames Append;
overriding procedure Read
(Buffer : in out Atom_Buffer;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Item'Length < Buffer.Used then
declare
Mutator : constant Atom_Refs.Mutator := Buffer.Ref.Update;
begin
Last := Item'Last;
Item := Mutator.Data.all (1 .. Item'Length);
Buffer.Used := Buffer.Used - Item'Length;
Mutator.Data.all (1 .. Buffer.Used) := Mutator.Data.all
(Item'Length + 1 .. Item'Length + Buffer.Used);
end;
else
Last := Item'First + Buffer.Used - 1;
Item (Item'First .. Last)
:= Buffer.Ref.Query.Data.all (1 .. Buffer.Used);
Buffer.Used := 0;
end if;
end Read;
end Natools.S_Expressions.Atom_Buffers;
|
fix stream read
|
s_expressions-atom_buffers: fix stream read
|
Ada
|
isc
|
faelys/natools
|
da7c7dc45bf6c099ec8c354a937ef8df6f09dcc1
|
regtests/ado-queries-tests.ads
|
regtests/ado-queries-tests.ads
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- 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 Util.Tests;
package ADO.Queries.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Load_Queries (T : in out Test);
-- Test the Initialize operation called several times
procedure Test_Initialize (T : in out Test);
-- Test the Set_Query operation.
procedure Test_Set_Query (T : in out Test);
-- Test the Set_Limit operation.
procedure Test_Set_Limit (T : in out Test);
-- Test the Find_Query operation.
procedure Test_Find_Query (T : in out Test);
end ADO.Queries.Tests;
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- 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 Util.Tests;
package ADO.Queries.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Load_Queries (T : in out Test);
-- Test re-loading queries.
procedure Test_Reload_Queries (T : in out Test);
-- Test the Initialize operation called several times
procedure Test_Initialize (T : in out Test);
-- Test the Set_Query operation.
procedure Test_Set_Query (T : in out Test);
-- Test the Set_Limit operation.
procedure Test_Set_Limit (T : in out Test);
-- Test the Find_Query operation.
procedure Test_Find_Query (T : in out Test);
end ADO.Queries.Tests;
|
Declare the Test_Reload_Queries procedure
|
Declare the Test_Reload_Queries procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
18f2f49d95c22c58c36e61f755d71bae7f1e21f1
|
regtests/ado-queries-tests.ads
|
regtests/ado-queries-tests.ads
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- 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 Util.Tests;
package ADO.Queries.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Load_Queries (T : in out Test);
-- Test re-loading queries.
procedure Test_Reload_Queries (T : in out Test);
-- Test the Initialize operation called several times
procedure Test_Initialize (T : in out Test);
-- Test the Set_Query operation.
procedure Test_Set_Query (T : in out Test);
-- Test the Set_Limit operation.
procedure Test_Set_Limit (T : in out Test);
-- Test the Find_Query operation.
procedure Test_Find_Query (T : in out Test);
end ADO.Queries.Tests;
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Queries.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Load_Queries (T : in out Test);
-- Test re-loading queries.
procedure Test_Reload_Queries (T : in out Test);
-- Test the Initialize operation called several times
procedure Test_Initialize (T : in out Test);
-- Test the Set_Query operation.
procedure Test_Set_Query (T : in out Test);
-- Test the Set_Limit operation.
procedure Test_Set_Limit (T : in out Test);
-- Test the Find_Query operation.
procedure Test_Find_Query (T : in out Test);
-- Test the missing query.
procedure Test_Missing_Query (T : in out Test);
end ADO.Queries.Tests;
|
Declare Test_Missing_Query procedure to test raising the Query_Error exception
|
Declare Test_Missing_Query procedure to test raising the Query_Error exception
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
5507d2bf23b8ca98d45dbb7fe3ae24e9d4a5799a
|
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
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
b36274fe0eb22cd42f119b73ed067e781911d8ce
|
src/security-oauth-clients.ads
|
src/security-oauth-clients.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package Security.OAuth.Clients is
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Get the application identifier.
function Get_Application_Identifier (App : in Application) return String;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Principal with record
Access_Id : String (1 .. Len);
end record;
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
Protect : Ada.Strings.Unbounded.Unbounded_String;
Key : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package Security.OAuth.Clients is
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private;
type OpenID_Token_Access is access all OpenID_Token'Class;
-- Get the id_token that was returned by the authentication process.
function Get_Id_Token (From : in OpenID_Token) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Get the application identifier.
function Get_Application_Identifier (App : in Application) return String;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Principal with record
Access_Id : String (1 .. Len);
end record;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record
Id_Token : String (1 .. Id_Len);
Refresh_Token : String (1 .. Refresh_Len);
end record;
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
Protect : Ada.Strings.Unbounded.Unbounded_String;
Key : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
Add support for OpenID Connect token
|
Add support for OpenID Connect token
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
df383bc12bfcae354c67600f0ba5d6d1989c7dd4
|
src/el-variables.adb
|
src/el-variables.adb
|
-----------------------------------------------------------------------
-- EL.Variables -- Variable mapper
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Variables is
-- ------------------------------
-- Get the Value_Expression that corresponds to the given variable name.
-- ------------------------------
function Get_Variable (Mapper : in Variable_Mapper'Class;
Name : in Unbounded_String)
return EL.Expressions.Value_Expression is
begin
return EL.Expressions.Create_Expression (Mapper.Get_Variable (Name));
end Get_Variable;
-- ------------------------------
-- Set the variable to the given value expression.
-- ------------------------------
procedure Set_Variable (Mapper : in out Variable_Mapper'Class;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
begin
Mapper.Set_Variable (Name, EL.Expressions.Expression (Value));
end Set_Variable;
end EL.Variables;
|
-----------------------------------------------------------------------
-- EL.Variables -- Variable mapper
-- 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.
-----------------------------------------------------------------------
package body EL.Variables is
-- ------------------------------
-- Get the Value_Expression that corresponds to the given variable name.
-- ------------------------------
function Get_Variable (Mapper : in Variable_Mapper'Class;
Name : in Unbounded_String)
return EL.Expressions.Value_Expression is
VE : constant EL.Expressions.Expression := Mapper.Get_Variable (Name);
begin
return EL.Expressions.Create_Expression (VE);
end Get_Variable;
-- ------------------------------
-- Set the variable to the given value expression.
-- ------------------------------
procedure Set_Variable (Mapper : in out Variable_Mapper'Class;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
begin
Mapper.Set_Variable (Name, EL.Expressions.Expression (Value));
end Set_Variable;
end EL.Variables;
|
Fix compilation with gcc 4.7
|
Fix compilation with gcc 4.7
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
c03560448207862d67b70c331c8339edfc8fac70
|
src/base/log/util-log-appenders-rolling_files.adb
|
src/base/log/util-log-appenders-rolling_files.adb
|
-----------------------------------------------------------------------
-- util-log-appenders-rolling_files -- Rolling file log appenders
-- Copyright (C) 2001 - 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.Finalization;
with Ada.Directories;
with Util.Properties.Basic;
with Util.Log.Appenders.Formatter;
package body Util.Log.Appenders.Rolling_Files is
use Ada;
use Ada.Finalization;
package Bool_Prop renames Util.Properties.Basic.Boolean_Property;
package Int_Prop renames Util.Properties.Basic.Integer_Property;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out File_Entity) is
begin
Text_IO.Close (File => Object.Output);
end Finalize;
protected body Rolling_File is
procedure Initialize (Name : in String;
Base : in String;
Properties : in Util.Properties.Manager) is
function Get_Policy return Util.Files.Rolling.Policy_Type with Inline;
function Get_Strategy return Util.Files.Rolling.Strategy_Type with Inline;
File : constant String := Properties.Get (Base & ".fileName", Name & ".log");
Pat : constant String := Properties.Get (Base & ".filePattern", Base & "-%i.log");
function Get_Policy return Util.Files.Rolling.Policy_Type is
Str : constant String := Properties.Get (Base & ".policy", "time");
Inter : constant Integer := Int_Prop.Get (Properties, Base & ".policyInterval", 1);
Size : constant String := Properties.Get (Base & ".minSize", "1000000");
begin
if Str = "none" then
return (Kind => Util.Files.Rolling.No_Policy);
elsif Str = "time" then
return (Kind => Util.Files.Rolling.Time_Policy,
Interval => Inter);
else
return (Kind => Util.Files.Rolling.Size_Policy,
Size => Ada.Directories.File_Size'Value (Size));
end if;
exception
when others =>
return (Kind => Util.Files.Rolling.No_Policy);
end Get_Policy;
function Get_Strategy return Util.Files.Rolling.Strategy_Type is
Str : constant String := Properties.Get (Base & ".strategy", "ascending");
Min : constant Integer := Int_Prop.Get (Properties, Base & ".policyMin", 0);
Max : constant Integer := Int_Prop.Get (Properties, Base & ".policyMax", 0);
begin
if Str = "direct" then
return (Kind => Util.Files.Rolling.Direct_Strategy,
Max_Files => Max);
elsif Str = "descending" then
return (Kind => Util.Files.Rolling.Descending_Strategy,
Min_Index => Min,
Max_Index => Max);
else
return (Kind => Util.Files.Rolling.Ascending_Strategy,
Min_Index => Min,
Max_Index => Max);
end if;
end Get_Strategy;
begin
Append := Bool_Prop.Get (Properties, Base & ".append", True);
Manager.Initialize (Path => File,
Pattern => Pat,
Policy => Get_Policy,
Strategy => Get_Strategy);
end Initialize;
procedure Openlog (File : out File_Refs.Ref) is
begin
if not Current.Is_Null then
if not Manager.Is_Rollover_Necessary then
File := Current;
return;
end if;
Closelog;
Manager.Rollover;
end if;
Current := File_Refs.Create;
declare
Path : constant String := Manager.Get_Current_Path;
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Path (Dir);
end if;
if not Ada.Directories.Exists (Path) then
Text_IO.Create (File => Current.Value.Output,
Name => Path);
else
Text_IO.Open (File => Current.Value.Output,
Name => Path,
Mode => (if Append then Text_IO.Append_File
else Text_IO.Out_File));
end if;
end;
end Openlog;
procedure Flush (File : out File_Refs.Ref) is
begin
if not Current.Is_Null then
File := Current;
end if;
end Flush;
procedure Closelog is
Empty : File_Refs.Ref;
begin
-- Close the current log by releasing its reference counter.
Current := Empty;
end Closelog;
end Rolling_File;
overriding
procedure Append (Self : in out File_Appender;
Message : in Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Level : in Level_Type;
Logger : in String) is
begin
if Self.Level >= Level then
declare
File : File_Refs.Ref;
procedure Write_File (Data : in String) with Inline_Always;
procedure Write_File (Data : in String) is
begin
Text_IO.Put (File.Value.Output, Data);
end Write_File;
procedure Write is new Formatter (Write_File);
begin
Self.File.Openlog (File);
if not File.Is_Null then
Write (Self, Message, Date, Level, Logger);
Text_IO.New_Line (File.Value.Output);
if Self.Immediate_Flush then
Text_IO.Flush (File.Value.Output);
end if;
end if;
end;
end if;
end Append;
-- ------------------------------
-- Flush the log events.
-- ------------------------------
overriding
procedure Flush (Self : in out File_Appender) is
File : File_Refs.Ref;
begin
Self.File.Flush (File);
if not File.Is_Null then
Text_IO.Flush (File.Value.Output);
end if;
end Flush;
-- ------------------------------
-- Flush and close the file.
-- ------------------------------
overriding
procedure Finalize (Self : in out File_Appender) is
begin
Self.File.Closelog;
end Finalize;
-- ------------------------------
-- Create a file appender and configure it according to the properties
-- ------------------------------
function Create (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access is
Base : constant String := "appender." & Name;
Result : constant File_Appender_Access
:= new File_Appender '(Limited_Controlled with Length => Name'Length,
Name => Name,
others => <>);
begin
Result.Set_Level (Name, Properties, Default);
Result.Set_Layout (Name, Properties, FULL);
Result.Immediate_Flush := Bool_Prop.Get (Properties, Base & ".immediateFlush", True);
Result.File.Initialize (Name, Base, Properties);
return Result.all'Access;
end Create;
end Util.Log.Appenders.Rolling_Files;
|
-----------------------------------------------------------------------
-- util-log-appenders-rolling_files -- Rolling file log appenders
-- Copyright (C) 2001 - 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.Finalization;
with Ada.Directories;
with Util.Properties.Basic;
with Util.Log.Appenders.Formatter;
package body Util.Log.Appenders.Rolling_Files is
use Ada;
use Ada.Finalization;
package Bool_Prop renames Util.Properties.Basic.Boolean_Property;
package Int_Prop renames Util.Properties.Basic.Integer_Property;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out File_Entity) is
begin
Text_IO.Close (File => Object.Output);
end Finalize;
protected body Rolling_File is
procedure Initialize (Name : in String;
Base : in String;
Properties : in Util.Properties.Manager) is
function Get_Policy return Util.Files.Rolling.Policy_Type with Inline;
function Get_Strategy return Util.Files.Rolling.Strategy_Type with Inline;
File : constant String := Properties.Get (Base & ".fileName", Name & ".log");
Pat : constant String := Properties.Get (Base & ".filePattern", Base & "-%i.log");
function Get_Policy return Util.Files.Rolling.Policy_Type is
Str : constant String := Properties.Get (Base & ".policy", "time");
Inter : constant Integer := Int_Prop.Get (Properties, Base & ".policyInterval", 1);
Size : constant String := Properties.Get (Base & ".minSize", "1000000");
begin
if Str = "none" then
return (Kind => Util.Files.Rolling.No_Policy);
elsif Str = "time" then
return (Kind => Util.Files.Rolling.Time_Policy,
Interval => Inter);
else
return (Kind => Util.Files.Rolling.Size_Policy,
Size => Ada.Directories.File_Size'Value (Size));
end if;
exception
when others =>
return (Kind => Util.Files.Rolling.No_Policy);
end Get_Policy;
function Get_Strategy return Util.Files.Rolling.Strategy_Type is
Str : constant String := Properties.Get (Base & ".strategy", "ascending");
Min : constant Integer := Int_Prop.Get (Properties, Base & ".policyMin", 0);
Max : constant Integer := Int_Prop.Get (Properties, Base & ".policyMax", 0);
begin
if Str = "direct" then
return (Kind => Util.Files.Rolling.Direct_Strategy,
Max_Files => Max);
elsif Str = "descending" then
return (Kind => Util.Files.Rolling.Descending_Strategy,
Min_Index => Min,
Max_Index => Max);
else
return (Kind => Util.Files.Rolling.Ascending_Strategy,
Min_Index => Min,
Max_Index => Max);
end if;
end Get_Strategy;
begin
Append := Bool_Prop.Get (Properties, Base & ".append", True);
Manager.Initialize (Path => File,
Pattern => Pat,
Policy => Get_Policy,
Strategy => Get_Strategy);
end Initialize;
procedure Openlog (File : out File_Refs.Ref) is
begin
if not Current.Is_Null then
if not Manager.Is_Rollover_Necessary then
File := Current;
return;
end if;
Closelog;
Manager.Rollover;
end if;
Current := File_Refs.Create;
declare
Path : constant String := Manager.Get_Current_Path;
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Path (Dir);
end if;
if not Ada.Directories.Exists (Path) then
Text_IO.Create (File => Current.Value.Output,
Name => Path);
else
Text_IO.Open (File => Current.Value.Output,
Name => Path,
Mode => (if Append then Text_IO.Append_File
else Text_IO.Out_File));
end if;
end;
end Openlog;
procedure Flush (File : out File_Refs.Ref) is
begin
if not Current.Is_Null then
File := Current;
end if;
end Flush;
procedure Closelog is
Empty : File_Refs.Ref;
begin
-- Close the current log by releasing its reference counter.
Current := Empty;
end Closelog;
end Rolling_File;
overriding
procedure Append (Self : in out File_Appender;
Message : in Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Level : in Level_Type;
Logger : in String) is
begin
if Self.Level >= Level then
declare
File : File_Refs.Ref;
procedure Write_File (Data : in String) with Inline_Always;
procedure Write_File (Data : in String) is
begin
Text_IO.Put (File.Value.Output, Data);
end Write_File;
procedure Write is new Formatter (Write_File);
begin
Self.File.Openlog (File);
if not File.Is_Null then
Write (Self, Message, Date, Level, Logger);
Text_IO.New_Line (File.Value.Output);
if Self.Immediate_Flush then
Text_IO.Flush (File.Value.Output);
end if;
end if;
end;
end if;
end Append;
-- ------------------------------
-- Flush the log events.
-- ------------------------------
overriding
procedure Flush (Self : in out File_Appender) is
File : File_Refs.Ref;
begin
Self.File.Flush (File);
if not File.Is_Null then
Text_IO.Flush (File.Value.Output);
end if;
end Flush;
-- ------------------------------
-- Flush and close the file.
-- ------------------------------
overriding
procedure Finalize (Self : in out File_Appender) is
begin
Self.File.Closelog;
end Finalize;
-- ------------------------------
-- Create a file appender and configure it according to the properties
-- ------------------------------
function Create (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access is
Base : constant String := "appender." & Name;
Result : constant File_Appender_Access
:= new File_Appender '(Limited_Controlled with Length => Name'Length,
Name => Name,
others => <>);
begin
Result.Set_Level (Name, Properties, Default);
Result.Set_Layout (Name, Properties, FULL);
Result.Immediate_Flush := Bool_Prop.Get (Properties, Base & ".immediateFlush", True);
Result.File.Initialize (Name, Base, Properties);
return Result.all'Access;
end Create;
end Util.Log.Appenders.Rolling_Files;
|
Fix indentation
|
Fix indentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
74810daa6f41a4a5e6488736d1db44cec09df918
|
src/util-streams.ads
|
src/util-streams.ads
|
-----------------------------------------------------------------------
-- Util.Streams -- Stream utilities
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- 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_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
-----------------------------------------------------------------------
-- Util.Streams -- Stream utilities
-- Copyright (C) 2010, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- 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_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String);
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
Declare the Copy procedure to copy a string to a Stream_Element_Array
|
Declare the Copy procedure to copy a string to a Stream_Element_Array
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ecdcc10bd1da96cbb006424e38e96ab1bda0c756
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Start_Element (P : in out Parser;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
procedure Start_Element (P : in out Parser;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
end Wiki.Parsers;
|
Declare the Parse_Text procedure
|
Declare the Parse_Text procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c07896268b3a1be5d6cb418504473e15530165a7
|
src/util-commands.ads
|
src/util-commands.ads
|
-----------------------------------------------------------------------
-- util-commands -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Commands is
-- The argument list interface that gives access to command arguments.
type Argument_List is limited interface;
-- Get the number of arguments available.
function Get_Count (List : in Argument_List) return Natural is abstract;
-- Get the argument at the given position.
function Get_Argument (List : in Argument_List;
Pos : in Positive) return String is abstract;
end Util.Commands;
|
-----------------------------------------------------------------------
-- util-commands -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Commands is
-- The argument list interface that gives access to command arguments.
type Argument_List is limited interface;
-- Get the number of arguments available.
function Get_Count (List : in Argument_List) return Natural is abstract;
-- Get the argument at the given position.
function Get_Argument (List : in Argument_List;
Pos : in Positive) return String is abstract;
type Default_Argument_List (Offset : Natural) is new Argument_List with null record;
-- Get the number of arguments available.
overriding
function Get_Count (List : in Default_Argument_List) return Natural;
-- Get the argument at the given position.
overriding
function Get_Argument (List : in Default_Argument_List;
Pos : in Positive) return String;
end Util.Commands;
|
Declare the Default_Argument_List and override the Get_Count and Get_Argument operations
|
Declare the Default_Argument_List and override the Get_Count and Get_Argument operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9dfba228420e2e0828ccbbade16ec3b25c7eea6d
|
src/dynamo.adb
|
src/dynamo.adb
|
-----------------------------------------------------------------------
-- 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 Util.Systems.Os;
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 (Util.Systems.Os.Path_Separator);
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;
|
-----------------------------------------------------------------------
-- dynamo -- Ada Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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 Util.Systems.Os;
with Util.Commands;
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;
First : Natural := 0;
-- ------------------------------
-- 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 (Util.Systems.Os.Path_Separator);
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 & "/");
First := First + 1;
when 't' =>
Template_Dir := To_Unbounded_String (Parameter & "/");
First := First + 1;
when 'c' =>
Set_Config_Directory (Parameter);
First := First + 1;
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;
First := First + 1;
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
use type Gen.Commands.Command_Access;
Args : Util.Commands.Default_Argument_List (First + 1);
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.Driver.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 (Cmd_Name, Args, 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;
|
Update to use the Ada Util command support
|
Update to use the Ada Util command support
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.