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
|
---|---|---|---|---|---|---|---|---|---|
624f09cb681cc206af3756e4e1a9386d7559d193
|
awa/src/awa-wikis-writers-html.adb
|
awa/src/awa-wikis-writers-html.adb
|
-----------------------------------------------------------------------
-- awa-wikis-writers -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body AWA.Wikis.Writers.Html is
use AWA.Wikis.Documents;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Writer) is
begin
Document.Writer.Start_Element ("br");
Document.Writer.End_Element ("br");
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Writer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Writer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Writer) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Writer) is
begin
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Writer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Writer.Write_Wide_Attribute ("href", Link);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Writer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Writer.Write_Wide_Attribute ("src", Link);
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end AWA.Wikis.Writers.Html;
|
-----------------------------------------------------------------------
-- awa-wikis-writers -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body AWA.Wikis.Writers.Html is
use AWA.Wikis.Documents;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Writer) is
begin
Document.Writer.Write_Raw ("<br />");
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Writer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Writer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Writer) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Writer) is
begin
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Writer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Writer.Write_Wide_Attribute ("href", Link);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Writer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Writer.Write_Wide_Attribute ("src", Link);
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end AWA.Wikis.Writers.Html;
|
Write the line break using <br /> instead of <br></br>
|
Write the line break using <br /> instead of <br></br>
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
1e3de755e5e9a3dcb73bdcd795763c770f3b62cc
|
awa/src/awa-wikis-writers-text.adb
|
awa/src/awa-wikis-writers-text.adb
|
-----------------------------------------------------------------------
-- awa-wikis-writers-text -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Wikis.Writers.Text is
use AWA.Wikis.Documents;
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Text_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Text_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
pragma Unreferenced (Level);
begin
Document.Close_Paragraph;
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Writer.Write (Header);
Document.Add_Line_Break;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Text_Writer) is
begin
Document.Writer.Write (ASCII.LF);
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Text_Writer;
Level : in Natural) is
begin
Document.Close_Paragraph;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Text_Writer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Writer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Writer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Text_Writer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
Document.Writer.Write (Name);
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Text_Writer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Text_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Text_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
end Finish;
end AWA.Wikis.Writers.Text;
|
-----------------------------------------------------------------------
-- awa-wikis-writers-text -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Wikis.Writers.Text is
use AWA.Wikis.Documents;
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Text_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Text_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
pragma Unreferenced (Level);
begin
Document.Close_Paragraph;
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Writer.Write (Header);
Document.Add_Line_Break;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Text_Writer) is
begin
Document.Writer.Write (ASCII.LF);
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Text_Writer;
Level : in Natural) is
begin
Document.Close_Paragraph;
for I in 1 .. Level loop
Document.Writer.Write (" ");
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Text_Writer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Writer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Writer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Text_Writer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
Document.Writer.Write (Name);
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Text_Writer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Text_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Text_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Writer) is
begin
Document.Close_Paragraph;
end Finish;
end AWA.Wikis.Writers.Text;
|
Indent the blockquote in the text output
|
Indent the blockquote in the text output
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
9b8760e342719007b9239531eedc770c32599826
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage instance stored in a folder and identified by a name.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage instance stored in a folder and identified by a name.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File);
-- Create a temporary file path.
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Temporary_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
Declare Create_Local_File for allocation of a temporary file
|
Declare Create_Local_File for allocation of a temporary file
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ea2b38df24b47350c44746fa8bd2ccae953fb714
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- 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.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- 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.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
Define POST_UID_ATTR
|
Define POST_UID_ATTR
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
df3f9b981865ac5e840647000e5b919fa2c3f0c0
|
awa/plugins/awa-storages/src/awa-storages.adb
|
awa/plugins/awa-storages/src/awa-storages.adb
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- 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.
-----------------------------------------------------------------------
package body AWA.Storages is
-- ------------------------------
-- Get the path to get access to the file.
-- ------------------------------
function Get_Path (File : in Storage_File) return String is
begin
return Ada.Strings.Unbounded.To_String (File.Path);
end Get_Path;
end AWA.Storages;
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
package body AWA.Storages is
-- ------------------------------
-- Get the path to get access to the file.
-- ------------------------------
function Get_Path (File : in Storage_File) return String is
begin
return Ada.Strings.Unbounded.To_String (File.Path);
end Get_Path;
-- ------------------------------
-- Get the path to get access to the file.
-- ------------------------------
function Get_Path (File : in Temporary_File) return String is
begin
return Ada.Strings.Unbounded.To_String (File.Path);
end Get_Path;
overriding
procedure Finalize (File : in out Temporary_File) is
Path : constant String := Ada.Strings.Unbounded.To_String (File.Path);
begin
if Path'Length > 0 and then Ada.Directories.Exists (Path) then
Ada.Directories.Delete_File (Path);
end if;
end Finalize;
end AWA.Storages;
|
Implement Get_Path and Finalize procedures for Temporary_File type
|
Implement Get_Path and Finalize procedures for Temporary_File type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0e3593d96955ede91df94ff0333795bbfbc71be5
|
awa/plugins/awa-votes/src/awa-votes-beans.adb
|
awa/plugins/awa-votes/src/awa-votes-beans.adb
|
-----------------------------------------------------------------------
-- awa-votes-beans -- Beans for module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Helpers.Requests;
package body AWA.Votes.Beans is
-- ------------------------------
-- Action to vote up.
-- ------------------------------
overriding
procedure Vote_Up (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := 1;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote_Up;
-- ------------------------------
-- Action to vote down.
-- ------------------------------
overriding
procedure Vote_Down (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := -1;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote_Down;
-- ------------------------------
-- Action to vote.
-- ------------------------------
overriding
procedure Vote (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := AWA.Helpers.Requests.Get_Parameter ("rating", 0);
if Bean.Rating /= 0 and Bean.Rating /= -1 and Bean.Rating /= 1 then
Bean.Rating := 0;
end if;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote;
-- ------------------------------
-- Create the Vote_Bean bean instance.
-- ------------------------------
function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Vote_Bean_Access := new Vote_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Vote_Bean;
end AWA.Votes.Beans;
|
-----------------------------------------------------------------------
-- awa-votes-beans -- Beans for module votes
-- Copyright (C) 2013, 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 AWA.Helpers.Requests;
package body AWA.Votes.Beans is
-- ------------------------------
-- Action to vote up.
-- ------------------------------
overriding
procedure Vote_Up (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := 1;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote_Up;
-- ------------------------------
-- Action to vote down.
-- ------------------------------
overriding
procedure Vote_Down (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := -1;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote_Down;
-- ------------------------------
-- Action to vote.
-- ------------------------------
overriding
procedure Vote (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Entity_Id := AWA.Helpers.Requests.Get_Parameter ("id");
Bean.Rating := AWA.Helpers.Requests.Get_Parameter ("rating", 0);
if Bean.Rating /= 0 and then Bean.Rating /= -1 and then Bean.Rating /= 1 then
Bean.Rating := 0;
end if;
Bean.Module.Vote_For (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Id => Bean.Entity_Id,
Value => Bean.Rating,
Total => Bean.Total);
end Vote;
-- ------------------------------
-- Create the Vote_Bean bean instance.
-- ------------------------------
function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Vote_Bean_Access := new Vote_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Vote_Bean;
end AWA.Votes.Beans;
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8a7af8167975f82636ab1bb06da2703386dfb6e4
|
mat/src/mat-readers-streams-sockets.ads
|
mat/src/mat-readers-streams-sockets.ads
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Streams.Buffered;
with Util.Streams.Files;
with Util.Streams.Sockets;
with GNAT.Sockets;
package MAT.Readers.Streams.Sockets is
type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private;
-- Initialize the socket listener.
overriding
procedure Initialize (Listener : in out Socket_Listener_Type);
-- Destroy the socket listener.
overriding
procedure Finalize (Listener : in out Socket_Listener_Type);
-- Open the socket to accept connections and start the listener task.
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
-- Stop the listener socket.
procedure Stop (Listener : in out Socket_Listener_Type);
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private;
type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
procedure Close (Reader : in out Socket_Reader_Type);
private
type Socket_Listener_Type_Access is access all Socket_Listener_Type;
task type Socket_Listener_Task is
entry Start (Listener : in Socket_Listener_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Listener_Task;
task type Socket_Reader_Task is
entry Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Reader_Task;
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record
Socket : aliased Util.Streams.Sockets.Socket_Stream;
Server : Socket_Reader_Task;
Stop : Boolean := False;
end record;
type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record
Accept_Selector : aliased GNAT.Sockets.Selector_Type;
Listener : Socket_Listener_Task;
end record;
end MAT.Readers.Streams.Sockets;
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Streams.Sockets;
with GNAT.Sockets;
package MAT.Readers.Streams.Sockets is
type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private;
-- Initialize the socket listener.
overriding
procedure Initialize (Listener : in out Socket_Listener_Type);
-- Destroy the socket listener.
overriding
procedure Finalize (Listener : in out Socket_Listener_Type);
-- Open the socket to accept connections and start the listener task.
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
-- Stop the listener socket.
procedure Stop (Listener : in out Socket_Listener_Type);
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private;
type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
procedure Close (Reader : in out Socket_Reader_Type);
private
type Socket_Listener_Type_Access is access all Socket_Listener_Type;
task type Socket_Listener_Task is
entry Start (Listener : in Socket_Listener_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Listener_Task;
task type Socket_Reader_Task is
entry Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Reader_Task;
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record
Socket : aliased Util.Streams.Sockets.Socket_Stream;
Server : Socket_Reader_Task;
Stop : Boolean := False;
end record;
type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record
Accept_Selector : aliased GNAT.Sockets.Selector_Type;
Listener : Socket_Listener_Task;
end record;
end MAT.Readers.Streams.Sockets;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1458176affd752f03dcb9fb47e456c349d38f7e0
|
src/gen-artifacts-docs-markdown.adb
|
src/gen-artifacts-docs-markdown.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Gen.Artifacts.Docs.Markdown is
function Has_Scheme (Link : in String) return Boolean;
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
if Text (Pos + 1) = '[' then
Start := Pos + 1;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- Write a line in the document.
-- ------------------------------
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String) is
begin
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
end Write_Line;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
case Line.Kind is
when L_LIST =>
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "#### " & Line.Content);
Formatter.Mode := L_TEXT;
when others =>
null;
end case;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Gen.Artifacts.Docs.Markdown is
function Has_Scheme (Link : in String) return Boolean;
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
pragma Unreferenced (Formatter);
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
pragma Unreferenced (Formatter);
begin
Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
pragma Unreferenced (Formatter);
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
if Text (Pos + 1) = '[' then
Start := Pos + 1;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- Write a line in the document.
-- ------------------------------
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String) is
begin
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
end Write_Line;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
case Line.Kind is
when L_LIST =>
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "#### " & Line.Content);
Formatter.Mode := L_TEXT;
when others =>
null;
end case;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
pragma Unreferenced (Formatter, Document);
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
d994b3f0207e47a8cde7b543ff0a186e24d0a126
|
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.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");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Questions_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
Plugin.Manager := Plugin.Create_Question_Manager;
end Initialize;
-- ------------------------------
-- Get the question manager.
-- ------------------------------
function Get_Question_Manager (Plugin : in Question_Module)
return Services.Question_Service_Access is
begin
return Plugin.Manager;
end Get_Question_Manager;
-- ------------------------------
-- 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 is
Result : constant Services.Question_Service_Access := new Services.Question_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Question_Manager;
-- ------------------------------
-- 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;
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 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");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Questions_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
Plugin.Manager := Plugin.Create_Question_Manager;
end Initialize;
-- ------------------------------
-- Get the question manager.
-- ------------------------------
function Get_Question_Manager (Plugin : in Question_Module)
return Services.Question_Service_Access is
begin
return Plugin.Manager;
end Get_Question_Manager;
-- ------------------------------
-- 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 is
Result : constant Services.Question_Service_Access := new Services.Question_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Question_Manager;
-- ------------------------------
-- 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;
-- ------------------------------
-- Get the question manager instance associated with the current application.
-- ------------------------------
function Get_Question_Manager return Services.Question_Service_Access is
Module : constant Question_Module_Access := Get_Question_Module;
begin
if Module = null then
Log.Error ("There is no active Question_Module");
return null;
else
return Module.Get_Question_Manager;
end if;
end Get_Question_Manager;
end AWA.Questions.Modules;
|
Implement the new function Get_Question_Manager
|
Implement the new function Get_Question_Manager
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bb63561b6c37d23586721bcabc30383d201337c2
|
awa/src/awa-events-configs-reader_config.ads
|
awa/src/awa-events-configs-reader_config.ads
|
-----------------------------------------------------------------------
-- awa-events-configs-reader_config -- Event configuration reader setup
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Serialize.Mappers;
with EL.Expressions;
with EL.Beans;
with EL.Contexts;
with ADO.Sessions;
with AWA.Events.Queues;
with AWA.Events.Services;
-- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description.
-- For example:
--
-- <dispatcher name="async">
-- <queue name="async"/>
-- <queue name="persist"/>
-- <count>4</count>
-- <priority>10</priority>
-- </dispatcher>
--
-- <queue name="async" type="fifo">
-- <property name="size">254</property>
-- </queue>
--
-- <queue name="defer" type="persist">
-- </queue>
--
-- <on-event name="create-user" queue="async">
-- <action>#{mail.send}</action>
-- <property name="user">#{event.name}</property>
-- <property name="template">mail/welcome.xhtml</property>
-- </on-event>
--
-- This defines an event action called when the <b>create-user</b> event is posted.
-- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and
-- <b>template</b> properties. The Ada bean action method <b>send</b> is called.
generic
Mapper : in out Util.Serialize.Mappers.Processing;
Manager : in AWA.Events.Services.Event_Manager_Access;
Context : in EL.Contexts.ELContext_Access;
package AWA.Events.Configs.Reader_Config is
Config : aliased Controller_Config;
procedure Initialize;
end AWA.Events.Configs.Reader_Config;
|
-----------------------------------------------------------------------
-- awa-events-configs-reader_config -- Event configuration reader setup
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers;
with EL.Contexts;
with AWA.Events.Services;
-- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description.
-- For example:
--
-- <dispatcher name="async">
-- <queue name="async"/>
-- <queue name="persist"/>
-- <count>4</count>
-- <priority>10</priority>
-- </dispatcher>
--
-- <queue name="async" type="fifo">
-- <property name="size">254</property>
-- </queue>
--
-- <queue name="defer" type="persist">
-- </queue>
--
-- <on-event name="create-user" queue="async">
-- <action>#{mail.send}</action>
-- <property name="user">#{event.name}</property>
-- <property name="template">mail/welcome.xhtml</property>
-- </on-event>
--
-- This defines an event action called when the <b>create-user</b> event is posted.
-- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and
-- <b>template</b> properties. The Ada bean action method <b>send</b> is called.
generic
Mapper : in out Util.Serialize.Mappers.Processing;
Manager : in AWA.Events.Services.Event_Manager_Access;
Context : in EL.Contexts.ELContext_Access;
package AWA.Events.Configs.Reader_Config is
Config : aliased Controller_Config;
procedure Initialize;
end AWA.Events.Configs.Reader_Config;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4f930ea161cae85e74fc53ecf12e8987cda9d0dc
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Quote : in Wide_Wide_Character;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = Quote;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
exit when C = '>';
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
P.Document.End_Element (Name);
else
Collect_Attributes (P);
P.Document.Start_Element (Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Quote : in Wide_Wide_Character;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = Quote;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
exit when C = '>';
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
Use the Start_Element and End_Element procedures on the Parser instance
|
Use the Start_Element and End_Element procedures on the Parser instance
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
3c8726185ba73da104ca76049874b814550cc89a
|
src/sys/encoders/util-encoders-hmac-sha256.ads
|
src/sys/encoders/util-encoders-hmac-sha256.ads
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code
-- 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 Util.Encoders.SHA256;
-- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA256 is
-- Sign the data string with the key and return the HMAC-SHA256 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Digest;
-- Sign the data string with the key and return the HMAC-SHA256 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest;
-- ------------------------------
-- HMAC-SHA256 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Hash_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Digest);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA256.Base64_Digest;
URL : in Boolean := False);
private
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA256.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA256;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code
-- Copyright (C) 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.Streams;
with Ada.Finalization;
with Util.Encoders.SHA256;
-- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA256 is
-- Sign the data string with the key and return the HMAC-SHA256 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA256.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA256 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest;
-- ------------------------------
-- HMAC-SHA256 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Hash_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Digest);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA256.Base64_Digest;
URL : in Boolean := False);
private
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA256.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA256;
|
Implement Sign procedure for PBKDF2
|
Implement Sign procedure for PBKDF2
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
20b001402acd520ed4e8e14962b1111a678a5632
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
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
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
Implement the Each_File procedure
|
Implement the Each_File procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
4d20e41edea3cfc60456fb4994c16c82186b024e
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp --
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
with Util.Files;
with Interfaces.C;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File) return Boolean is
begin
return Element.Status /= FILE_UNCHANGED;
end Is_Modified;
overriding
procedure Add_File (Into : in out File_Queue;
Path : in String;
Element : in File) is
begin
Into.Queue.Enqueue (Element);
end Add_File;
overriding
procedure Add_Directory (Into : in out File_Queue;
Path : in String;
Name : in String) is
begin
Into.Directories.Append (Util.Files.Compose (Path, Name));
end Add_Directory;
procedure Compute_Sha1 (Path : in String;
Into : in out File) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Name : constant String := Path & "/" & To_String (Into.Name);
Last : Ada.Streams.Stream_Element_Offset;
Buf : Ada.Streams.Stream_Element_Array (0 .. 32_767);
Ctx : Util.Encoders.SHA1.Context;
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name);
loop
Ada.Streams.Stream_IO.Read (File, Buf, Last);
Util.Encoders.SHA1.Update (Ctx, Buf (Buf'First .. Last));
exit when Last /= Buf'Last;
end loop;
Ada.Streams.Stream_IO.Close (File);
Util.Encoders.SHA1.Finish (Ctx, Into.SHA1);
end Compute_Sha1;
procedure Iterate_Files (Path : in String;
Dir : in out Directory;
Depth : in Natural;
Update : access procedure (P : in String; F : in out File)) is
use Ada.Strings.Unbounded;
Iter : File_Vectors.Cursor := Dir.Files.First;
procedure Iterate_File (Item : in out File) is
begin
Update (Path, Item);
end Iterate_File;
procedure Iterate_Child (Item : in out Directory) is
begin
Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update);
end Iterate_Child;
begin
while File_Vectors.Has_Element (Iter) loop
Dir.Files.Update_Element (Iter, Iterate_File'Access);
File_Vectors.Next (Iter);
end loop;
if Depth > 0 and then Dir.Children /= null then
declare
Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First;
begin
while Directory_Vectors.Has_Element (Dir_Iter) loop
Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access);
Directory_Vectors.Next (Dir_Iter);
end loop;
end;
end if;
end Iterate_Files;
procedure Scan_Files (Path : in String;
Into : in out Directory) is
Iter : File_Vectors.Cursor := Into.Files.First;
procedure Compute_Sha1 (Item : in out File) is
begin
Compute_Sha1 (Path, Item);
end Compute_Sha1;
begin
while File_Vectors.Has_Element (Iter) loop
Into.Files.Update_Element (Iter, Compute_Sha1'Access);
File_Vectors.Next (Iter);
end loop;
end Scan_Files;
procedure Scan_Children (Path : in String;
Into : in out Directory) is
procedure Update (Dir : in out Directory) is
use Ada.Strings.Unbounded;
use type Ada.Directories.File_Size;
begin
Scan (Path & "/" & To_String (Dir.Name), Dir);
Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files;
Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size;
Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs;
end Update;
begin
if Into.Children /= null then
declare
Iter : Directory_Vectors.Cursor := Into.Children.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Into.Children.Update_Element (Iter, Update'Access);
Directory_Vectors.Next (Iter);
end loop;
end;
end if;
end Scan_Children;
procedure Scan (Path : in String;
Into : in out Directory) is
use Ada.Directories;
Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
New_File : File;
Child : Directory;
begin
Into.Tot_Size := 0;
Into.Tot_Files := 0;
Into.Tot_Dirs := 0;
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
begin
if Kind = Ordinary_File then
New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
begin
New_File.Size := Ada.Directories.Size (Ent);
exception
when Constraint_Error =>
New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last);
end;
Into.Files.Append (New_File);
if New_File.Size > 0 then
begin
Into.Tot_Size := Into.Tot_Size + New_File.Size;
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size)
& " for " & Path & "/" & Name);
Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size));
end;
end if;
Into.Tot_Files := Into.Tot_Files + 1;
elsif Name /= "." and Name /= ".." then
if Into.Children = null then
Into.Children := new Directory_Vector;
end if;
Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Into.Children.Append (Child);
Into.Tot_Dirs := Into.Tot_Dirs + 1;
end if;
end;
end loop;
Scan_Children (Path, Into);
Scan_Files (Path, Into);
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
with Util.Files;
with Interfaces.C;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File) return Boolean is
begin
return Element.Status /= FILE_UNCHANGED;
end Is_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File) return String is
begin
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path),
Ada.Strings.Unbounded.To_String (Element.Name));
end Get_Path;
overriding
procedure Add_File (Into : in out File_Queue;
Path : in String;
Element : in File) is
begin
Into.Queue.Enqueue (Element);
end Add_File;
overriding
procedure Add_Directory (Into : in out File_Queue;
Path : in String;
Name : in String) is
begin
Into.Directories.Append (Util.Files.Compose (Path, Name));
end Add_Directory;
procedure Compute_Sha1 (Path : in String;
Into : in out File) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Name : constant String := Path & "/" & To_String (Into.Name);
Last : Ada.Streams.Stream_Element_Offset;
Buf : Ada.Streams.Stream_Element_Array (0 .. 32_767);
Ctx : Util.Encoders.SHA1.Context;
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name);
loop
Ada.Streams.Stream_IO.Read (File, Buf, Last);
Util.Encoders.SHA1.Update (Ctx, Buf (Buf'First .. Last));
exit when Last /= Buf'Last;
end loop;
Ada.Streams.Stream_IO.Close (File);
Util.Encoders.SHA1.Finish (Ctx, Into.SHA1);
end Compute_Sha1;
procedure Iterate_Files (Path : in String;
Dir : in out Directory;
Depth : in Natural;
Update : access procedure (P : in String; F : in out File)) is
use Ada.Strings.Unbounded;
Iter : File_Vectors.Cursor := Dir.Files.First;
procedure Iterate_File (Item : in out File) is
begin
Update (Path, Item);
end Iterate_File;
procedure Iterate_Child (Item : in out Directory) is
begin
Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update);
end Iterate_Child;
begin
while File_Vectors.Has_Element (Iter) loop
Dir.Files.Update_Element (Iter, Iterate_File'Access);
File_Vectors.Next (Iter);
end loop;
if Depth > 0 and then Dir.Children /= null then
declare
Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First;
begin
while Directory_Vectors.Has_Element (Dir_Iter) loop
Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access);
Directory_Vectors.Next (Dir_Iter);
end loop;
end;
end if;
end Iterate_Files;
procedure Scan_Files (Path : in String;
Into : in out Directory) is
Iter : File_Vectors.Cursor := Into.Files.First;
procedure Compute_Sha1 (Item : in out File) is
begin
Compute_Sha1 (Path, Item);
end Compute_Sha1;
begin
while File_Vectors.Has_Element (Iter) loop
Into.Files.Update_Element (Iter, Compute_Sha1'Access);
File_Vectors.Next (Iter);
end loop;
end Scan_Files;
procedure Scan_Children (Path : in String;
Into : in out Directory) is
procedure Update (Dir : in out Directory) is
use Ada.Strings.Unbounded;
use type Ada.Directories.File_Size;
begin
Scan (Path & "/" & To_String (Dir.Name), Dir);
Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files;
Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size;
Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs;
end Update;
begin
if Into.Children /= null then
declare
Iter : Directory_Vectors.Cursor := Into.Children.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Into.Children.Update_Element (Iter, Update'Access);
Directory_Vectors.Next (Iter);
end loop;
end;
end if;
end Scan_Children;
procedure Scan (Path : in String;
Into : in out Directory) is
use Ada.Directories;
Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
New_File : File;
Child : Directory;
begin
Into.Tot_Size := 0;
Into.Tot_Files := 0;
Into.Tot_Dirs := 0;
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
begin
if Kind = Ordinary_File then
New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
begin
New_File.Size := Ada.Directories.Size (Ent);
exception
when Constraint_Error =>
New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last);
end;
Into.Files.Append (New_File);
if New_File.Size > 0 then
begin
Into.Tot_Size := Into.Tot_Size + New_File.Size;
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size)
& " for " & Path & "/" & Name);
Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size));
end;
end if;
Into.Tot_Files := Into.Tot_Files + 1;
elsif Name /= "." and Name /= ".." then
if Into.Children = null then
Into.Children := new Directory_Vector;
end if;
Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Into.Children.Append (Child);
Into.Tot_Dirs := Into.Tot_Dirs + 1;
end if;
end;
end loop;
Scan_Children (Path, Into);
Scan_Files (Path, Into);
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
end Babel.Files;
|
Implement the Get_Path function
|
Implement the Get_Path function
|
Ada
|
apache-2.0
|
stcarrez/babel
|
d31650a536fc63d50eac3ef7c8ab720c70b6362d
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "03";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc7";
compiler_version : constant String := "7.3.0";
previous_compiler : constant String := "7.2.0";
binutils_version : constant String := "2.30";
previous_binutils : constant String := "2.29.1";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "04";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc7";
compiler_version : constant String := "7.3.0";
previous_compiler : constant String := "7.2.0";
binutils_version : constant String := "2.30";
previous_binutils : constant String := "2.29.1";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version
|
Bump version
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
0717c4968a3e7def8fdeb760cba17036c886e9d3
|
matp/src/events/mat-events-targets.ads
|
matp/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
Define the Finalize procedure to finalize the Target_Events type
|
Define the Finalize procedure to finalize the Target_Events type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1b68a9da36b909e5be4467ca467d2354c84705e2
|
src/base/files/util-files-rolling.ads
|
src/base/files/util-files-rolling.ads
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- 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 Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file; the `Interval` configuration
-- defines the period to check for time changes,
-- * `Size_Time_Policy`: combines the size and time policy, the rolling is
-- triggered when either the file reaches a given size or the date/time
-- pattern no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy, Size_Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Time_Policy | Size_Policy | Size_Time_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
Interval : Natural := 0;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file referred by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in out File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are eligible to purge in the given directory.
procedure Eligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in File_Manager;
Old : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- 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 Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file; the `Interval` configuration
-- defines the period to check for time changes,
-- * `Size_Time_Policy`: combines the size and time policy, the rolling is
-- triggered when either the file reaches a given size or the date/time
-- pattern no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy, Size_Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Time_Policy | Size_Policy | Size_Time_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
Interval : Natural := 0;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file referred by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in out File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are eligible to purge in the given directory.
procedure Eligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in out File_Manager;
Old : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Last_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
Add Last_Path and record it when Rename is called
|
Add Last_Path and record it when Rename is called
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
75d8836cebdf979fae81a3cdf4c2f9cdd47614ce
|
src/babel-stores.ads
|
src/babel-stores.ads
|
-----------------------------------------------------------------------
-- babel-stores -- Storage management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Filters;
with Babel.Streams;
with Babel.Streams.Refs;
package Babel.Stores is
type Store_Type is limited interface;
type Store_Type_Access is access all Store_Type'Class;
-- Open a file in the store to read its content with a stream.
procedure Open_File (Store : in out Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is abstract;
-- Open a file in the store to read its content with a stream.
procedure Read_File (Store : in out Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref) is abstract;
-- Write a file in the store with a stream.
procedure Write_File (Store : in out Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Util.Systems.Types.mode_t) is abstract;
procedure Read (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is abstract;
procedure Write (Store : in out Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is abstract;
procedure Scan (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is abstract;
end Babel.Stores;
|
-----------------------------------------------------------------------
-- babel-stores -- Storage management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Filters;
with Babel.Streams;
with Babel.Streams.Refs;
package Babel.Stores is
type Store_Type is limited interface;
type Store_Type_Access is access all Store_Type'Class;
-- Open a file in the store to read its content with a stream.
procedure Open_File (Store : in out Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is abstract;
-- Open a file in the store to read its content with a stream.
procedure Read_File (Store : in out Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref) is abstract;
-- Write a file in the store with a stream.
procedure Write_File (Store : in out Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Babel.Files.File_Mode) is abstract;
procedure Read (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is abstract;
procedure Write (Store : in out Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is abstract;
procedure Scan (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is abstract;
end Babel.Stores;
|
Change Write_File to use the Babel.Files.File_Mode type
|
Change Write_File to use the Babel.Files.File_Mode type
|
Ada
|
apache-2.0
|
stcarrez/babel
|
9f642b271b5a200c553bce4c6e87b66377642aa3
|
awt/src/shared/awt-inputs-gamepads-mappings.adb
|
awt/src/shared/awt-inputs-gamepads-mappings.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
with Orka.Strings;
with Orka.Logging;
package body AWT.Inputs.Gamepads.Mappings is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
package SF renames Ada.Strings.Fixed;
function GUID_Hash (Key : GUID_String) return Ada.Containers.Hash_Type is
(Ada.Strings.Hash (String (Key)));
package Mapping_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => GUID_String,
Element_Type => String,
Hash => GUID_Hash,
Equivalent_Keys => "=");
Mappings : Mapping_Maps.Map;
procedure Set_Mappings (Platform : Platform_Kind; Text : String) is
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Platform_Value : constant String :=
(case Platform is
when Linux => "Linux",
when Windows => "Windows",
when Mac_OS_X => "Mac OS X",
when iOS => "iOS",
when Android => "Android");
Platform_String : constant String := ",platform:" & Platform_Value & ",";
Count : Natural := 0;
use type SU.Unbounded_String;
begin
for Line of Lines loop
declare
Mapping : constant Orka.Strings.String_List := Orka.Strings.Split (+Line, ",", 2);
begin
if Mapping'Length = 2 and SU.Index (Line, "#") /= 1 then
declare
GUID : constant String := (+Mapping (1));
Value : constant String := (+Mapping (2));
Value_Without_Platform : String renames
Value (Value'First .. Value'Last - Platform_String'Length);
Platform : String renames
Value (Value'Last - Platform_String'Length + 1 .. Value'Last);
pragma Assert (GUID = "xinput" or GUID'Length = GUID_String'Length);
begin
if Platform = Platform_String and GUID /= "xinput" then
Mappings.Insert (GUID_String (GUID), Value_Without_Platform);
Count := Count + 1;
end if;
end;
end if;
end;
end loop;
Messages.Log (Debug,
"Added " & Trim (Count'Image) & " gamepad mappings for " & Platform_Value & " platform");
end Set_Mappings;
function Contains (GUID : GUID_String) return Boolean is
(Mappings.Contains (GUID));
function Get (GUID : GUID_String) return String is (Mappings (GUID));
function Name_To_Output (Name : String) return Output_Mapping is
begin
-- Buttons
if Name = "a" then
return (Kind => Button, Button => Action_Down);
elsif Name = "b" then
return (Kind => Button, Button => Action_Right);
elsif Name = "x" then
return (Kind => Button, Button => Action_Left);
elsif Name = "y" then
return (Kind => Button, Button => Action_Up);
elsif Name = "dpup" then
return (Kind => Button, Button => Direction_Up);
elsif Name = "dpright" then
return (Kind => Button, Button => Direction_Right);
elsif Name = "dpdown" then
return (Kind => Button, Button => Direction_Down);
elsif Name = "dpleft" then
return (Kind => Button, Button => Direction_Left);
elsif Name = "leftshoulder" then
return (Kind => Button, Button => Shoulder_Left);
elsif Name = "rightshoulder" then
return (Kind => Button, Button => Shoulder_Right);
elsif Name = "back" then
return (Kind => Button, Button => Center_Left);
elsif Name = "start" then
return (Kind => Button, Button => Center_Right);
elsif Name = "guide" then
return (Kind => Button, Button => Center_Logo);
elsif Name = "leftstick" then
return (Kind => Button, Button => Thumb_Left);
elsif Name = "rightstick" then
return (Kind => Button, Button => Thumb_Right);
-- Axes
elsif Name = "leftx" then
return (Kind => Axis, Axis => Stick_Left_X, others => <>);
elsif Name = "lefty" then
return (Kind => Axis, Axis => Stick_Left_Y, others => <>);
elsif Name = "rightx" then
return (Kind => Axis, Axis => Stick_Right_X, others => <>);
elsif Name = "righty" then
return (Kind => Axis, Axis => Stick_Right_Y, others => <>);
-- Triggers
elsif Name = "lefttrigger" then
return (Kind => Trigger, Trigger => Trigger_Left);
elsif Name = "righttrigger" then
return (Kind => Trigger, Trigger => Trigger_Right);
else
raise Constraint_Error;
end if;
end Name_To_Output;
function Parse_Mapping
(Line : String;
Set_Mapping : not null access procedure
(Kind : Mapping_Kind;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
Name : String)) return String
is
Index : constant Natural := SF.Index (Line, ",");
pragma Assert (Index > 0);
Name : constant String := Line (Line'First .. Index - 1);
Value : constant String := Line (Index + 1 .. Line'Last);
begin
for Mapping of Orka.Strings.Split (Value, ",") loop
declare
Button_Input : constant Orka.Strings.String_List := Orka.Strings.Split (+Mapping, ":");
pragma Assert (Button_Input'Length = 2);
Button : constant String := (+Button_Input (1));
Input : constant String := (+Button_Input (2));
Index : Natural := Button'First;
Last : Natural := Input'Last;
Output_Positive : Boolean := False;
Output_Negative : Boolean := False;
Input_Positive : Boolean := False;
Input_Negative : Boolean := False;
Input_Invert : Boolean := False;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
begin
-- Each mapping has the following format:
--
-- [+|-]<output>:[+|-]<input>[~]
--
-- The output is the name of a button, axis, or trigger.
-- (See function Name_To_Output above)
--
-- The input starts with an 'a' (axis), 'b' (button), or 'h' (hat)
-- followed by a natural number.
--
-- The '+' or '-' character just after the ':' is only used
-- if the input is an axis.
--
-- (output +/- only for non-triggers)
-- output: '-': map final input to -1 .. 0
-- | '+': map final input to 0 .. 1
-- | (empty): map final input to -1 .. 1
-- v
-- +leftx:h0.2,-leftx:h0.8
-- lefttrigger:a3~
-- dpleft:-a0 ^
-- ^ |
-- | invert input: map normalized input from 0 .. 1 to 1 .. 0
-- |
-- input: '-': if axis is in negative half, use and normalize input to 0 .. 1
-- '+': if axis is in positive half, use and normalize input to 0 .. 1
if Button (Index) = '+' then
Output_Positive := True;
Index := Index + 1;
elsif Button (Index) = '-' then
Output_Negative := True;
Index := Index + 1;
end if;
Output_Map := Name_To_Output (Button (Index .. Button'Last));
if Output_Map.Kind = Axis then
if Output_Positive then
Output_Map.Scale := 1.0;
Output_Map.Offset := 0.0;
elsif Output_Negative then
Output_Map.Scale := -1.0;
Output_Map.Offset := 0.0;
end if;
end if;
Index := Input'First;
if Input (Index) in '+' then
Input_Positive := True;
Index := Index + 1;
elsif Input (Index) in '-' then
Input_Negative := True;
Index := Index + 1;
end if;
if Input (Last) in '~' then
Input_Invert := True;
Last := Last - 1;
end if;
if Input (Index) = 'a' then
if Input_Positive then
Input_Map.Side := Positive_Half;
elsif Input_Negative then
Input_Map.Side := Negative_Half;
end if;
if Input_Invert then
Input_Map.Invert := True;
end if;
Set_Mapping (Axis_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'b' then
Set_Mapping (Button_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'h' then
Set_Mapping (Hat_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
else
raise Constraint_Error;
end if;
end;
end loop;
return Name;
end Parse_Mapping;
end AWT.Inputs.Gamepads.Mappings;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
with Orka.Strings;
with Orka.Logging;
package body AWT.Inputs.Gamepads.Mappings is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
package SF renames Ada.Strings.Fixed;
function GUID_Hash (Key : GUID_String) return Ada.Containers.Hash_Type is
(Ada.Strings.Hash (String (Key)));
package Mapping_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => GUID_String,
Element_Type => String,
Hash => GUID_Hash,
Equivalent_Keys => "=");
Mappings : Mapping_Maps.Map;
procedure Set_Mappings (Platform : Platform_Kind; Text : String) is
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Platform_Value : constant String :=
(case Platform is
when Linux => "Linux",
when Windows => "Windows",
when Mac_OS_X => "Mac OS X",
when iOS => "iOS",
when Android => "Android");
Platform_String : constant String := ",platform:" & Platform_Value & ",";
Count : Natural := 0;
use type SU.Unbounded_String;
begin
for Line of Lines loop
declare
Mapping : constant Orka.Strings.String_List := Orka.Strings.Split (+Line, ",", 2);
begin
if Mapping'Length = 2 and SU.Index (Line, "#") /= 1 then
declare
GUID : constant String := (+Mapping (1));
Value : constant String := (+Mapping (2));
Value_Without_Platform : String renames
Value (Value'First .. Value'Last - Platform_String'Length);
Platform : String renames
Value (Value'Last - Platform_String'Length + 1 .. Value'Last);
pragma Assert (GUID = "xinput" or GUID'Length = GUID_String'Length);
begin
if Platform = Platform_String and GUID /= "xinput" then
Mappings.Insert (GUID_String (GUID), Value_Without_Platform);
Count := Count + 1;
end if;
end;
end if;
end;
end loop;
Messages.Log (Debug,
"Added " & Trim (Count'Image) & " gamepad mappings for " & Platform_Value & " platform");
end Set_Mappings;
function Contains (GUID : GUID_String) return Boolean is
(Mappings.Contains (GUID));
function Get (GUID : GUID_String) return String is (Mappings (GUID));
function Name_To_Output (Name : String) return Output_Mapping is
begin
-- Buttons
if Name = "a" then
return (Kind => Button, Button => Action_Down);
elsif Name = "b" then
return (Kind => Button, Button => Action_Right);
elsif Name = "x" then
return (Kind => Button, Button => Action_Left);
elsif Name = "y" then
return (Kind => Button, Button => Action_Up);
elsif Name = "dpup" then
return (Kind => Button, Button => Direction_Up);
elsif Name = "dpright" then
return (Kind => Button, Button => Direction_Right);
elsif Name = "dpdown" then
return (Kind => Button, Button => Direction_Down);
elsif Name = "dpleft" then
return (Kind => Button, Button => Direction_Left);
elsif Name = "leftshoulder" then
return (Kind => Button, Button => Shoulder_Left);
elsif Name = "rightshoulder" then
return (Kind => Button, Button => Shoulder_Right);
elsif Name = "back" then
return (Kind => Button, Button => Center_Left);
elsif Name = "start" then
return (Kind => Button, Button => Center_Right);
elsif Name = "guide" then
return (Kind => Button, Button => Center_Logo);
elsif Name = "leftstick" then
return (Kind => Button, Button => Thumb_Left);
elsif Name = "rightstick" then
return (Kind => Button, Button => Thumb_Right);
-- Axes
elsif Name = "leftx" then
return (Kind => Axis, Axis => Stick_Left_X, others => <>);
elsif Name = "lefty" then
return (Kind => Axis, Axis => Stick_Left_Y, others => <>);
elsif Name = "rightx" then
return (Kind => Axis, Axis => Stick_Right_X, others => <>);
elsif Name = "righty" then
return (Kind => Axis, Axis => Stick_Right_Y, others => <>);
-- Triggers
elsif Name = "lefttrigger" then
return (Kind => Trigger, Trigger => Trigger_Left);
elsif Name = "righttrigger" then
return (Kind => Trigger, Trigger => Trigger_Right);
else
raise Constraint_Error;
end if;
end Name_To_Output;
function Parse_Mapping
(Line : String;
Set_Mapping : not null access procedure
(Kind : Mapping_Kind;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
Name : String)) return String
is
Index : constant Natural := SF.Index (Line, ",");
pragma Assert (Index > 0);
Name : constant String := Line (Line'First .. Index - 1);
Value : constant String := Line (Index + 1 .. Line'Last);
begin
for Mapping of Orka.Strings.Split (Value, ",") loop
declare
Output_Input : constant Orka.Strings.String_List := Orka.Strings.Split (+Mapping, ":");
pragma Assert (Output_Input'Length = 2);
Output : constant String := (+Output_Input (1));
Input : constant String := (+Output_Input (2));
Index : Natural := Output'First;
Last : Natural := Input'Last;
Output_Positive : Boolean := False;
Output_Negative : Boolean := False;
Input_Positive : Boolean := False;
Input_Negative : Boolean := False;
Input_Invert : Boolean := False;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
begin
-- Each mapping has the following format:
--
-- [+|-]<output>:[+|-]<input>[~]
--
-- The output is the name of a button, axis, or trigger.
-- (See function Name_To_Output above)
--
-- The input starts with an 'a' (axis), 'b' (button), or 'h' (hat)
-- followed by a natural number.
--
-- The '+' or '-' character just after the ':' is only used
-- if the input is an axis.
--
-- (output +/- only for non-triggers)
-- output: '-': map final input to -1 .. 0
-- | '+': map final input to 0 .. 1
-- | (empty): map final input to -1 .. 1
-- v
-- +leftx:h0.2,-leftx:h0.8
-- lefttrigger:a3~
-- dpleft:-a0 ^
-- ^ |
-- | invert input: map normalized input from 0 .. 1 to 1 .. 0
-- |
-- input: '-': if axis is in negative half, use and normalize input to 0 .. 1
-- '+': if axis is in positive half, use and normalize input to 0 .. 1
if Output (Index) = '+' then
Output_Positive := True;
Index := Index + 1;
elsif Output (Index) = '-' then
Output_Negative := True;
Index := Index + 1;
end if;
Output_Map := Name_To_Output (Output (Index .. Output'Last));
if Output_Map.Kind = Axis then
if Output_Positive then
Output_Map.Scale := 1.0;
Output_Map.Offset := 0.0;
elsif Output_Negative then
Output_Map.Scale := -1.0;
Output_Map.Offset := 0.0;
end if;
end if;
Index := Input'First;
if Input (Index) in '+' then
Input_Positive := True;
Index := Index + 1;
elsif Input (Index) in '-' then
Input_Negative := True;
Index := Index + 1;
end if;
if Input (Last) in '~' then
Input_Invert := True;
Last := Last - 1;
end if;
if Input (Index) = 'a' then
if Input_Positive then
Input_Map.Side := Positive_Half;
elsif Input_Negative then
Input_Map.Side := Negative_Half;
end if;
if Input_Invert then
Input_Map.Invert := True;
end if;
Set_Mapping (Axis_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'b' then
Set_Mapping (Button_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'h' then
Set_Mapping (Hat_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
else
raise Constraint_Error;
end if;
end;
end loop;
return Name;
end Parse_Mapping;
end AWT.Inputs.Gamepads.Mappings;
|
Rename some variables in function Parse_Mapping
|
awt: Rename some variables in function Parse_Mapping
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
be93f0643cfd2437bd2ab12482c8d6d2164bbd24
|
awt/src/shared/awt-inputs-gamepads-mappings.adb
|
awt/src/shared/awt-inputs-gamepads-mappings.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
with Orka.Strings;
with Orka.Logging;
package body AWT.Inputs.Gamepads.Mappings is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
package SF renames Ada.Strings.Fixed;
function GUID_Hash (Key : GUID_String) return Ada.Containers.Hash_Type is
(Ada.Strings.Hash (String (Key)));
package Mapping_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => GUID_String,
Element_Type => String,
Hash => GUID_Hash,
Equivalent_Keys => "=");
Mappings : Mapping_Maps.Map;
procedure Set_Mappings (Platform : Platform_Kind; Text : String) is
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Platform_Value : constant String :=
(case Platform is
when Linux => "Linux",
when Windows => "Windows",
when Mac_OS_X => "Mac OS X",
when iOS => "iOS",
when Android => "Android");
Platform_String : constant String := ",platform:" & Platform_Value & ",";
Count : Natural := 0;
use type SU.Unbounded_String;
begin
for Line of Lines loop
declare
Mapping : constant Orka.Strings.String_List := Orka.Strings.Split (+Line, ",", 2);
begin
if Mapping'Length = 2 and SU.Index (Line, "#") /= 1 then
declare
GUID : constant String := (+Mapping (1));
Value : constant String := (+Mapping (2));
Value_Without_Platform : String renames
Value (Value'First .. Value'Last - Platform_String'Length);
Platform : String renames
Value (Value'Last - Platform_String'Length + 1 .. Value'Last);
pragma Assert (GUID = "xinput" or GUID'Length = GUID_String'Length);
begin
if Platform = Platform_String and GUID /= "xinput" then
Mappings.Insert (GUID_String (GUID), Value_Without_Platform);
Count := Count + 1;
end if;
end;
end if;
end;
end loop;
Messages.Log (Debug,
"Added " & Trim (Count'Image) & " gamepad mappings for " & Platform_Value & " platform");
end Set_Mappings;
function Contains (GUID : GUID_String) return Boolean is
(Mappings.Contains (GUID));
function Get (GUID : GUID_String) return String is (Mappings (GUID));
function Name_To_Output (Name : String) return Output_Mapping is
begin
-- Buttons
if Name = "a" then
return (Kind => Button, Button => Action_Down);
elsif Name = "b" then
return (Kind => Button, Button => Action_Right);
elsif Name = "x" then
return (Kind => Button, Button => Action_Left);
elsif Name = "y" then
return (Kind => Button, Button => Action_Up);
elsif Name = "dpup" then
return (Kind => Button, Button => Direction_Up);
elsif Name = "dpright" then
return (Kind => Button, Button => Direction_Right);
elsif Name = "dpdown" then
return (Kind => Button, Button => Direction_Down);
elsif Name = "dpleft" then
return (Kind => Button, Button => Direction_Left);
elsif Name = "leftshoulder" then
return (Kind => Button, Button => Shoulder_Left);
elsif Name = "rightshoulder" then
return (Kind => Button, Button => Shoulder_Right);
elsif Name = "back" then
return (Kind => Button, Button => Center_Left);
elsif Name = "start" then
return (Kind => Button, Button => Center_Right);
elsif Name = "guide" then
return (Kind => Button, Button => Center_Logo);
elsif Name = "leftstick" then
return (Kind => Button, Button => Thumb_Left);
elsif Name = "rightstick" then
return (Kind => Button, Button => Thumb_Right);
-- Axes
elsif Name = "leftx" then
return (Kind => Axis, Axis => Stick_Left_X, others => <>);
elsif Name = "lefty" then
return (Kind => Axis, Axis => Stick_Left_Y, others => <>);
elsif Name = "rightx" then
return (Kind => Axis, Axis => Stick_Right_X, others => <>);
elsif Name = "righty" then
return (Kind => Axis, Axis => Stick_Right_Y, others => <>);
-- Triggers
elsif Name = "lefttrigger" then
return (Kind => Trigger, Trigger => Trigger_Left);
elsif Name = "righttrigger" then
return (Kind => Trigger, Trigger => Trigger_Right);
else
raise Constraint_Error;
end if;
end Name_To_Output;
function Parse_Mapping
(Line : String;
Set_Mapping : not null access procedure
(Kind : Mapping_Kind;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
Name : String)) return String
is
Index : constant Natural := SF.Index (Line, ",");
pragma Assert (Index > 0);
Name : constant String := Line (Line'First .. Index - 1);
Value : constant String := Line (Index + 1 .. Line'Last);
begin
for Mapping of Orka.Strings.Split (Value, ",") loop
declare
Button_Input : constant Orka.Strings.String_List := Orka.Strings.Split (+Mapping, ":");
pragma Assert (Button_Input'Length = 2);
Button : constant String := (+Button_Input (1));
Input : constant String := (+Button_Input (2));
Index : Natural := Button'First;
Last : Natural := Input'Last;
Output_Positive : Boolean := False;
Output_Negative : Boolean := False;
Input_Positive : Boolean := False;
Input_Negative : Boolean := False;
Input_Invert : Boolean := False;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
begin
if Button (Index) = '+' then
Output_Positive := True;
Index := Index + 1;
elsif Button (Index) = '-' then
Output_Negative := True;
Index := Index + 1;
end if;
Output_Map := Name_To_Output (Button (Index .. Button'Last));
if Output_Map.Kind = Axis then
if Output_Positive then
Output_Map.Scale := 1.0;
Output_Map.Offset := 0.0;
elsif Output_Negative then
Output_Map.Scale := -1.0;
Output_Map.Offset := 0.0;
end if;
end if;
Index := Input'First;
if Input (Index) in '+' then
Input_Positive := True;
Index := Index + 1;
elsif Input (Index) in '-' then
Input_Negative := True;
Index := Index + 1;
end if;
if Input (Last) in '~' then
Input_Invert := True;
Last := Last - 1;
end if;
if Input (Index) = 'a' then
if Input_Positive then
Input_Map.Side := Positive_Half;
elsif Input_Negative then
Input_Map.Side := Negative_Half;
end if;
if Input_Invert then
Input_Map.Invert := True;
end if;
Set_Mapping (Axis_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'b' then
Set_Mapping (Button_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'h' then
Set_Mapping (Hat_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
else
raise Constraint_Error;
end if;
end;
end loop;
return Name;
end Parse_Mapping;
end AWT.Inputs.Gamepads.Mappings;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
with Orka.Strings;
with Orka.Logging;
package body AWT.Inputs.Gamepads.Mappings is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
package SF renames Ada.Strings.Fixed;
function GUID_Hash (Key : GUID_String) return Ada.Containers.Hash_Type is
(Ada.Strings.Hash (String (Key)));
package Mapping_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => GUID_String,
Element_Type => String,
Hash => GUID_Hash,
Equivalent_Keys => "=");
Mappings : Mapping_Maps.Map;
procedure Set_Mappings (Platform : Platform_Kind; Text : String) is
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Platform_Value : constant String :=
(case Platform is
when Linux => "Linux",
when Windows => "Windows",
when Mac_OS_X => "Mac OS X",
when iOS => "iOS",
when Android => "Android");
Platform_String : constant String := ",platform:" & Platform_Value & ",";
Count : Natural := 0;
use type SU.Unbounded_String;
begin
for Line of Lines loop
declare
Mapping : constant Orka.Strings.String_List := Orka.Strings.Split (+Line, ",", 2);
begin
if Mapping'Length = 2 and SU.Index (Line, "#") /= 1 then
declare
GUID : constant String := (+Mapping (1));
Value : constant String := (+Mapping (2));
Value_Without_Platform : String renames
Value (Value'First .. Value'Last - Platform_String'Length);
Platform : String renames
Value (Value'Last - Platform_String'Length + 1 .. Value'Last);
pragma Assert (GUID = "xinput" or GUID'Length = GUID_String'Length);
begin
if Platform = Platform_String and GUID /= "xinput" then
Mappings.Insert (GUID_String (GUID), Value_Without_Platform);
Count := Count + 1;
end if;
end;
end if;
end;
end loop;
Messages.Log (Debug,
"Added " & Trim (Count'Image) & " gamepad mappings for " & Platform_Value & " platform");
end Set_Mappings;
function Contains (GUID : GUID_String) return Boolean is
(Mappings.Contains (GUID));
function Get (GUID : GUID_String) return String is (Mappings (GUID));
function Name_To_Output (Name : String) return Output_Mapping is
begin
-- Buttons
if Name = "a" then
return (Kind => Button, Button => Action_Down);
elsif Name = "b" then
return (Kind => Button, Button => Action_Right);
elsif Name = "x" then
return (Kind => Button, Button => Action_Left);
elsif Name = "y" then
return (Kind => Button, Button => Action_Up);
elsif Name = "dpup" then
return (Kind => Button, Button => Direction_Up);
elsif Name = "dpright" then
return (Kind => Button, Button => Direction_Right);
elsif Name = "dpdown" then
return (Kind => Button, Button => Direction_Down);
elsif Name = "dpleft" then
return (Kind => Button, Button => Direction_Left);
elsif Name = "leftshoulder" then
return (Kind => Button, Button => Shoulder_Left);
elsif Name = "rightshoulder" then
return (Kind => Button, Button => Shoulder_Right);
elsif Name = "back" then
return (Kind => Button, Button => Center_Left);
elsif Name = "start" then
return (Kind => Button, Button => Center_Right);
elsif Name = "guide" then
return (Kind => Button, Button => Center_Logo);
elsif Name = "leftstick" then
return (Kind => Button, Button => Thumb_Left);
elsif Name = "rightstick" then
return (Kind => Button, Button => Thumb_Right);
-- Axes
elsif Name = "leftx" then
return (Kind => Axis, Axis => Stick_Left_X, others => <>);
elsif Name = "lefty" then
return (Kind => Axis, Axis => Stick_Left_Y, others => <>);
elsif Name = "rightx" then
return (Kind => Axis, Axis => Stick_Right_X, others => <>);
elsif Name = "righty" then
return (Kind => Axis, Axis => Stick_Right_Y, others => <>);
-- Triggers
elsif Name = "lefttrigger" then
return (Kind => Trigger, Trigger => Trigger_Left);
elsif Name = "righttrigger" then
return (Kind => Trigger, Trigger => Trigger_Right);
else
raise Constraint_Error;
end if;
end Name_To_Output;
function Parse_Mapping
(Line : String;
Set_Mapping : not null access procedure
(Kind : Mapping_Kind;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
Name : String)) return String
is
Index : constant Natural := SF.Index (Line, ",");
pragma Assert (Index > 0);
Name : constant String := Line (Line'First .. Index - 1);
Value : constant String := Line (Index + 1 .. Line'Last);
begin
for Mapping of Orka.Strings.Split (Value, ",") loop
declare
Button_Input : constant Orka.Strings.String_List := Orka.Strings.Split (+Mapping, ":");
pragma Assert (Button_Input'Length = 2);
Button : constant String := (+Button_Input (1));
Input : constant String := (+Button_Input (2));
Index : Natural := Button'First;
Last : Natural := Input'Last;
Output_Positive : Boolean := False;
Output_Negative : Boolean := False;
Input_Positive : Boolean := False;
Input_Negative : Boolean := False;
Input_Invert : Boolean := False;
Input_Map : Input_Mapping;
Output_Map : Output_Mapping;
begin
-- Each mapping has the following format:
--
-- [+|-]<output>:[+|-]<input>[~]
--
-- The output is the name of a button, axis, or trigger.
-- (See function Name_To_Output above)
--
-- The input starts with an 'a' (axis), 'b' (button), or 'h' (hat)
-- followed by a natural number.
--
-- The '+' or '-' character just after the ':' is only used
-- if the input is an axis.
--
-- (output +/- only for non-triggers)
-- output: '-': map final input to -1 .. 0
-- | '+': map final input to 0 .. 1
-- | (empty): map final input to -1 .. 1
-- v
-- +leftx:h0.2,-leftx:h0.8
-- lefttrigger:a3~
-- dpleft:-a0 ^
-- ^ |
-- | invert input: map normalized input from 0 .. 1 to 1 .. 0
-- |
-- input: '-': if axis is in negative half, use and normalize input to 0 .. 1
-- '+': if axis is in positive half, use and normalize input to 0 .. 1
if Button (Index) = '+' then
Output_Positive := True;
Index := Index + 1;
elsif Button (Index) = '-' then
Output_Negative := True;
Index := Index + 1;
end if;
Output_Map := Name_To_Output (Button (Index .. Button'Last));
if Output_Map.Kind = Axis then
if Output_Positive then
Output_Map.Scale := 1.0;
Output_Map.Offset := 0.0;
elsif Output_Negative then
Output_Map.Scale := -1.0;
Output_Map.Offset := 0.0;
end if;
end if;
Index := Input'First;
if Input (Index) in '+' then
Input_Positive := True;
Index := Index + 1;
elsif Input (Index) in '-' then
Input_Negative := True;
Index := Index + 1;
end if;
if Input (Last) in '~' then
Input_Invert := True;
Last := Last - 1;
end if;
if Input (Index) = 'a' then
if Input_Positive then
Input_Map.Side := Positive_Half;
elsif Input_Negative then
Input_Map.Side := Negative_Half;
end if;
if Input_Invert then
Input_Map.Invert := True;
end if;
Set_Mapping (Axis_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'b' then
Set_Mapping (Button_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
elsif Input (Index) = 'h' then
Set_Mapping (Hat_Mapping, Input_Map, Output_Map, Input (Index + 1 .. Last));
else
raise Constraint_Error;
end if;
end;
end loop;
return Name;
end Parse_Mapping;
end AWT.Inputs.Gamepads.Mappings;
|
Add comment in code describing format of gamepad mappings
|
awt: Add comment in code describing format of gamepad mappings
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
61537cf630dffede25e99907957873b257616e92
|
matp/src/memory/mat-memory-targets.ads
|
matp/src/memory/mat-memory-targets.ads
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
with MAT.Events.Probes;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural := 0;
Total_Alloc : MAT.Types.Target_Size := 0;
Total_Free : MAT.Types.Target_Size := 0;
Malloc_Count : Natural := 0;
Free_Count : Natural := 0;
Realloc_Count : Natural := 0;
end record;
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
private
protected type Memory_Allocator is
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Regions : Region_Info_Map;
Stats : Memory_Stat;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
with MAT.Events.Probes;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural := 0;
Total_Alloc : MAT.Types.Target_Size := 0;
Total_Free : MAT.Types.Target_Size := 0;
Malloc_Count : Natural := 0;
Free_Count : Natural := 0;
Realloc_Count : Natural := 0;
end record;
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
private
protected type Memory_Allocator is
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Regions : Region_Info_Map;
Stats : Memory_Stat;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
Change the Slot parameter of Probe_Free to an in out parameter
|
Change the Slot parameter of Probe_Free to an in out parameter
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7d11137f49e10ca1b0dd90d6d4486cf951ec22ec
|
src/asf-components-html-factory.adb
|
src/asf-components-html-factory.adb
|
-----------------------------------------------------------------------
-- html-factory -- Factory for HTML UI Components
-- Copyright (C) 2009, 2010, 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Base;
with ASF.Components.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Components.Html.Links;
with ASF.Components.Html.Panels;
with ASF.Components.Html.Forms;
with ASF.Components.Html.Pages;
with ASF.Components.Html.Selects;
with ASF.Components.Html.Messages;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
use ASF.Components.Base;
function Create_Body return UIComponent_Access;
function Create_Doctype return UIComponent_Access;
function Create_Head return UIComponent_Access;
function Create_Output return UIComponent_Access;
function Create_Output_Label return UIComponent_Access;
function Create_Output_Link return UIComponent_Access;
function Create_Output_Format return UIComponent_Access;
function Create_List return UIComponent_Access;
function Create_PanelGroup return UIComponent_Access;
function Create_Form return UIComponent_Access;
function Create_Input_File return UIComponent_Access;
function Create_Input_Hidden return UIComponent_Access;
function Create_Input_Text return UIComponent_Access;
function Create_Input_Textarea return UIComponent_Access;
function Create_Command return UIComponent_Access;
function Create_Message return UIComponent_Access;
function Create_Messages return UIComponent_Access;
function Create_SelectOne return UIComponent_Access;
function Create_SelectOneRadio return UIComponent_Access;
function Create_SelectBooleanCheckbox return UIComponent_Access;
-- Create an UIInput secret component
function Create_Input_Secret return ASF.Components.Base.UIComponent_Access;
-- ------------------------------
-- Create an UIBody component
-- ------------------------------
function Create_Body return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIBody;
end Create_Body;
-- ------------------------------
-- Create an UIDoctype component
-- ------------------------------
function Create_Doctype return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIDoctype;
end Create_Doctype;
-- ------------------------------
-- Create an UIHead component
-- ------------------------------
function Create_Head return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIHead;
end Create_Head;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutput;
end Create_Output;
-- ------------------------------
-- Create an UIOutputLabel component
-- ------------------------------
function Create_Output_Label return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputLabel;
end Create_Output_Label;
-- ------------------------------
-- Create an UIOutputLink component
-- ------------------------------
function Create_Output_Link return UIComponent_Access is
begin
return new ASF.Components.Html.Links.UIOutputLink;
end Create_Output_Link;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output_Format return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputFormat;
end Create_Output_Format;
-- ------------------------------
-- Create an UIList component
-- ------------------------------
function Create_List return UIComponent_Access is
begin
return new ASF.Components.Html.Lists.UIList;
end Create_List;
-- ------------------------------
-- Create an UIPanelGroup component
-- ------------------------------
function Create_PanelGroup return UIComponent_Access is
begin
return new ASF.Components.Html.Panels.UIPanelGroup;
end Create_PanelGroup;
-- ------------------------------
-- Create an UIForm component
-- ------------------------------
function Create_Form return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIForm;
end Create_Form;
-- ------------------------------
-- Create an UIInput_Hidden component
-- ------------------------------
function Create_Input_Hidden return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput_Hidden;
end Create_Input_Hidden;
-- ------------------------------
-- Create an UIInput component
-- ------------------------------
function Create_Input_Text return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput;
end Create_Input_Text;
-- ------------------------------
-- Create an UIInput secret component
-- ------------------------------
function Create_Input_Secret return ASF.Components.Base.UIComponent_Access is
Result : constant Html.Forms.UIInput_Access := new ASF.Components.Html.Forms.UIInput;
begin
Result.Set_Secret (True);
return Result.all'Access;
end Create_Input_Secret;
-- ------------------------------
-- Create an UIInputTextarea component
-- ------------------------------
function Create_Input_Textarea return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInputTextarea;
end Create_Input_Textarea;
-- ------------------------------
-- Create an UIInput_File component
-- ------------------------------
function Create_Input_File return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput_File;
end Create_Input_File;
-- ------------------------------
-- Create an UICommand component
-- ------------------------------
function Create_Command return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UICommand;
end Create_Command;
-- ------------------------------
-- Create an UIMessage component
-- ------------------------------
function Create_Message return UIComponent_Access is
begin
return new ASF.Components.Html.Messages.UIMessage;
end Create_Message;
-- ------------------------------
-- Create an UIMessages component
-- ------------------------------
function Create_Messages return UIComponent_Access is
begin
return new ASF.Components.Html.Messages.UIMessages;
end Create_Messages;
-- ------------------------------
-- Create an UISelectOne component
-- ------------------------------
function Create_SelectOne return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectOne;
end Create_SelectOne;
-- ------------------------------
-- Create an UISelectOneRadio component
-- ------------------------------
function Create_SelectOneRadio return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectOneRadio;
end Create_SelectOneRadio;
-- ------------------------------
-- Create an UISelectBoolean component
-- ------------------------------
function Create_SelectBooleanCheckbox return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectBoolean;
end Create_SelectBooleanCheckbox;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
BODY_TAG : aliased constant String := "body";
COMMAND_BUTTON_TAG : aliased constant String := "commandButton";
DOCTYPE_TAG : aliased constant String := "doctype";
FORM_TAG : aliased constant String := "form";
HEAD_TAG : aliased constant String := "head";
INPUT_FILE_TAG : aliased constant String := "inputFile";
INPUT_HIDDEN_TAG : aliased constant String := "inputHidden";
INPUT_SECRET_TAG : aliased constant String := "inputSecret";
INPUT_TEXT_TAG : aliased constant String := "inputText";
INPUT_TEXTAREA_TAG : aliased constant String := "inputTextarea";
LIST_TAG : aliased constant String := "list";
MESSAGE_TAG : aliased constant String := "message";
MESSAGES_TAG : aliased constant String := "messages";
OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat";
OUTPUT_LABEL_TAG : aliased constant String := "outputLabel";
OUTPUT_LINK_TAG : aliased constant String := "outputLink";
OUTPUT_TEXT_TAG : aliased constant String := "outputText";
PANEL_GROUP_TAG : aliased constant String := "panelGroup";
SELECT_BOOLEAN_TAG : aliased constant String := "selectBooleanCheckbox";
SELECT_ONE_MENU_TAG : aliased constant String := "selectOneMenu";
SELECT_ONE_RADIO_TAG : aliased constant String := "selectOneRadio";
Html_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => BODY_TAG'Access,
Component => Create_Body'Access,
Tag => Create_Component_Node'Access),
2 => (Name => COMMAND_BUTTON_TAG'Access,
Component => Create_Command'Access,
Tag => Create_Component_Node'Access),
3 => (Name => DOCTYPE_TAG'Access,
Component => Create_Doctype'Access,
Tag => Create_Component_Node'Access),
4 => (Name => FORM_TAG'Access,
Component => Create_Form'Access,
Tag => Create_Component_Node'Access),
5 => (Name => HEAD_TAG'Access,
Component => Create_Head'Access,
Tag => Create_Component_Node'Access),
6 => (Name => INPUT_FILE_TAG'Access,
Component => Create_Input_File'Access,
Tag => Create_Component_Node'Access),
7 => (Name => INPUT_HIDDEN_TAG'Access,
Component => Create_Input_Hidden'Access,
Tag => Create_Component_Node'Access),
8 => (Name => INPUT_SECRET_TAG'Access,
Component => Create_Input_Secret'Access,
Tag => Create_Component_Node'Access),
9 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input_Text'Access,
Tag => Create_Component_Node'Access),
10 => (Name => INPUT_TEXTAREA_TAG'Access,
Component => Create_Input_Textarea'Access,
Tag => Create_Component_Node'Access),
11 => (Name => LIST_TAG'Access,
Component => Create_List'Access,
Tag => Create_Component_Node'Access),
12 => (Name => MESSAGE_TAG'Access,
Component => Create_Message'Access,
Tag => Create_Component_Node'Access),
13 => (Name => MESSAGES_TAG'Access,
Component => Create_Messages'Access,
Tag => Create_Component_Node'Access),
14 => (Name => OUTPUT_FORMAT_TAG'Access,
Component => Create_Output_Format'Access,
Tag => Create_Component_Node'Access),
15 => (Name => OUTPUT_LABEL_TAG'Access,
Component => Create_Output_Label'Access,
Tag => Create_Component_Node'Access),
16 => (Name => OUTPUT_LINK_TAG'Access,
Component => Create_Output_Link'Access,
Tag => Create_Component_Node'Access),
17 => (Name => OUTPUT_TEXT_TAG'Access,
Component => Create_Output'Access,
Tag => Create_Component_Node'Access),
18 => (Name => PANEL_GROUP_TAG'Access,
Component => Create_PanelGroup'Access,
Tag => Create_Component_Node'Access),
19 => (Name => SELECT_BOOLEAN_TAG'Access,
Component => Create_SelectBooleanCheckbox'Access,
Tag => Create_Component_Node'Access),
20 => (Name => SELECT_ONE_MENU_TAG'Access,
Component => Create_SelectOne'Access,
Tag => Create_Component_Node'Access),
21 => (Name => SELECT_ONE_RADIO_TAG'Access,
Component => Create_SelectOneRadio'Access,
Tag => Create_Component_Node'Access)
);
Html_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Html_Bindings'Access);
-- ------------------------------
-- Get the HTML component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Html_Factory'Access;
end Definition;
end ASF.Components.Html.Factory;
|
-----------------------------------------------------------------------
-- html-factory -- Factory for HTML UI Components
-- Copyright (C) 2009, 2010, 2011, 2012, 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 ASF.Components.Base;
with ASF.Components.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Components.Html.Links;
with ASF.Components.Html.Panels;
with ASF.Components.Html.Forms;
with ASF.Components.Html.Pages;
with ASF.Components.Html.Selects;
with ASF.Components.Html.Messages;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
use ASF.Components.Base;
function Create_Body return UIComponent_Access;
function Create_Doctype return UIComponent_Access;
function Create_Head return UIComponent_Access;
function Create_Output return UIComponent_Access;
function Create_Output_Label return UIComponent_Access;
function Create_Output_Link return UIComponent_Access;
function Create_Output_Format return UIComponent_Access;
function Create_List return UIComponent_Access;
function Create_PanelGroup return UIComponent_Access;
function Create_Form return UIComponent_Access;
function Create_Input_File return UIComponent_Access;
function Create_Input_Hidden return UIComponent_Access;
function Create_Input_Text return UIComponent_Access;
function Create_Input_Textarea return UIComponent_Access;
function Create_Command return UIComponent_Access;
function Create_Message return UIComponent_Access;
function Create_Messages return UIComponent_Access;
function Create_SelectOne return UIComponent_Access;
function Create_SelectOneRadio return UIComponent_Access;
function Create_SelectBooleanCheckbox return UIComponent_Access;
-- Create an UIInput secret component
function Create_Input_Secret return ASF.Components.Base.UIComponent_Access;
-- ------------------------------
-- Create an UIBody component
-- ------------------------------
function Create_Body return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIBody;
end Create_Body;
-- ------------------------------
-- Create an UIDoctype component
-- ------------------------------
function Create_Doctype return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIDoctype;
end Create_Doctype;
-- ------------------------------
-- Create an UIHead component
-- ------------------------------
function Create_Head return UIComponent_Access is
begin
return new ASF.Components.Html.Pages.UIHead;
end Create_Head;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutput;
end Create_Output;
-- ------------------------------
-- Create an UIOutputLabel component
-- ------------------------------
function Create_Output_Label return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputLabel;
end Create_Output_Label;
-- ------------------------------
-- Create an UIOutputLink component
-- ------------------------------
function Create_Output_Link return UIComponent_Access is
begin
return new ASF.Components.Html.Links.UIOutputLink;
end Create_Output_Link;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output_Format return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputFormat;
end Create_Output_Format;
-- ------------------------------
-- Create an UIList component
-- ------------------------------
function Create_List return UIComponent_Access is
begin
return new ASF.Components.Html.Lists.UIList;
end Create_List;
-- ------------------------------
-- Create an UIPanelGroup component
-- ------------------------------
function Create_PanelGroup return UIComponent_Access is
begin
return new ASF.Components.Html.Panels.UIPanelGroup;
end Create_PanelGroup;
-- ------------------------------
-- Create an UIForm component
-- ------------------------------
function Create_Form return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIForm;
end Create_Form;
-- ------------------------------
-- Create an UIInput_Hidden component
-- ------------------------------
function Create_Input_Hidden return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput_Hidden;
end Create_Input_Hidden;
-- ------------------------------
-- Create an UIInput component
-- ------------------------------
function Create_Input_Text return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput;
end Create_Input_Text;
-- ------------------------------
-- Create an UIInput secret component
-- ------------------------------
function Create_Input_Secret return ASF.Components.Base.UIComponent_Access is
Result : constant Html.Forms.UIInput_Access := new ASF.Components.Html.Forms.UIInput;
begin
Result.Set_Secret (True);
return Result.all'Access;
end Create_Input_Secret;
-- ------------------------------
-- Create an UIInputTextarea component
-- ------------------------------
function Create_Input_Textarea return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInputTextarea;
end Create_Input_Textarea;
-- ------------------------------
-- Create an UIInput_File component
-- ------------------------------
function Create_Input_File return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput_File;
end Create_Input_File;
-- ------------------------------
-- Create an UICommand component
-- ------------------------------
function Create_Command return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UICommand;
end Create_Command;
-- ------------------------------
-- Create an UIMessage component
-- ------------------------------
function Create_Message return UIComponent_Access is
begin
return new ASF.Components.Html.Messages.UIMessage;
end Create_Message;
-- ------------------------------
-- Create an UIMessages component
-- ------------------------------
function Create_Messages return UIComponent_Access is
begin
return new ASF.Components.Html.Messages.UIMessages;
end Create_Messages;
-- ------------------------------
-- Create an UISelectOne component
-- ------------------------------
function Create_SelectOne return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectOne;
end Create_SelectOne;
-- ------------------------------
-- Create an UISelectOneRadio component
-- ------------------------------
function Create_SelectOneRadio return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectOneRadio;
end Create_SelectOneRadio;
-- ------------------------------
-- Create an UISelectBoolean component
-- ------------------------------
function Create_SelectBooleanCheckbox return UIComponent_Access is
begin
return new ASF.Components.Html.Selects.UISelectBoolean;
end Create_SelectBooleanCheckbox;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
BODY_TAG : aliased constant String := "body";
COMMAND_BUTTON_TAG : aliased constant String := "commandButton";
DOCTYPE_TAG : aliased constant String := "doctype";
FORM_TAG : aliased constant String := "form";
HEAD_TAG : aliased constant String := "head";
INPUT_FILE_TAG : aliased constant String := "inputFile";
INPUT_HIDDEN_TAG : aliased constant String := "inputHidden";
INPUT_SECRET_TAG : aliased constant String := "inputSecret";
INPUT_TEXT_TAG : aliased constant String := "inputText";
INPUT_TEXTAREA_TAG : aliased constant String := "inputTextarea";
LIST_TAG : aliased constant String := "list";
MESSAGE_TAG : aliased constant String := "message";
MESSAGES_TAG : aliased constant String := "messages";
OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat";
OUTPUT_LABEL_TAG : aliased constant String := "outputLabel";
OUTPUT_LINK_TAG : aliased constant String := "outputLink";
OUTPUT_TEXT_TAG : aliased constant String := "outputText";
PANEL_GROUP_TAG : aliased constant String := "panelGroup";
SELECT_BOOLEAN_TAG : aliased constant String := "selectBooleanCheckbox";
SELECT_ONE_MENU_TAG : aliased constant String := "selectOneMenu";
SELECT_ONE_RADIO_TAG : aliased constant String := "selectOneRadio";
-- ------------------------------
-- Get the HTML component factory.
-- ------------------------------
procedure Register (Factory : in out ASF.Factory.Component_Factory) is
begin
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => BODY_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Body'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => COMMAND_BUTTON_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Command'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => DOCTYPE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Doctype'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => FORM_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Form'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => HEAD_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Head'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_FILE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_File'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_HIDDEN_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Hidden'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_SECRET_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Secret'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_TEXT_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Text'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_TEXTAREA_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Textarea'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => LIST_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_List'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => MESSAGE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Message'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => MESSAGES_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Messages'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => OUTPUT_FORMAT_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Output_Format'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => OUTPUT_LABEL_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Output_Label'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => OUTPUT_LINK_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Output_Link'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => OUTPUT_TEXT_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Output'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => PANEL_GROUP_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_PanelGroup'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => SELECT_BOOLEAN_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_SelectBooleanCheckbox'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => SELECT_ONE_MENU_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_SelectOne'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => SELECT_ONE_RADIO_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_SelectOneRadio'Access);
end Register;
end ASF.Components.Html.Factory;
|
Change the Definition function into a Register procedure
|
Change the Definition function into a Register procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
de8616cd4cb349480c5ad58dad7d90f5f2936aac
|
matp/src/events/mat-events-targets.ads
|
matp/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Next_Id : Event_Id_Type := 0;
Prev_Id : Event_Id_Type := 0;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type);
-- 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 (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- 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 (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type);
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
procedure Insert (Event : in out Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Next_Id : Event_Id_Type := 0;
Prev_Id : Event_Id_Type := 0;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
Alloc_Size : MAT.Types.Target_Size := 0;
Free_Size : MAT.Types.Target_Size := 0;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type);
-- 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 (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- 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 (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type);
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
procedure Insert (Event : in out Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
Add Alloc_Size and Free_Size in the Event_Info record
|
Add Alloc_Size and Free_Size in the Event_Info record
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a3a2fb220760b839cdfeb7dfb5e8d454abd423c7
|
src/ado-sessions.ads
|
src/ado-sessions.ads
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- 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 Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Drivers.Connections;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
-- It provides operation to create a database statement that can be executed.
-- The <tt>Session</tt> type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- The database connection status
type Connection_Status is (OPEN, CLOSED);
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return Connection_Status;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access;
-- Close the session.
procedure Close (Database : in out Session);
-- Insert a new cache in the manager. The cache is identified by the given name.
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access);
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Drivers.Connections.Ref.Ref;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Drivers.Connections;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
-- It provides operation to create a database statement that can be executed.
-- The <tt>Session</tt> type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- The database connection status
type Connection_Status is (OPEN, CLOSED);
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return Connection_Status;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access;
-- Close the session.
procedure Close (Database : in out Session);
-- Insert a new cache in the manager. The cache is identified by the given name.
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access);
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Drivers.Connections.Ref.Ref;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
Fix compilation warning detected by GNAT 2017
|
Fix compilation warning detected by GNAT 2017
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
7288c395f1feebbf364166ea9a11a6b86a371cfc
|
src/http/aws/util-http-clients-web.ads
|
src/http/aws/util-http-clients-web.ads
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with null record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
type AWS_Http_Request is new Http_Request with record
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String;
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
end Util.Http.Clients.Web;
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with null record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
type AWS_Http_Request is new Http_Request with record
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String;
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
end Util.Http.Clients.Web;
|
Implement the Do_Put procedure
|
Implement the Do_Put procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5e84a08ce30e9b8f3456fbde97a5b4e13f4ed9d0
|
src/asf-principals.ads
|
src/asf-principals.ads
|
-----------------------------------------------------------------------
-- asf-principals -- Component and tag factory
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Permissions;
package ASF.Principals is
-- ------------------------------
-- Principal
-- ------------------------------
subtype Principal is Security.Permissions.Principal;
subtype Principal_Access is Security.Permissions.Principal_Access;
end ASF.Principals;
|
-----------------------------------------------------------------------
-- asf-principals -- Component and tag factory
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security;
package ASF.Principals is
-- ------------------------------
-- Principal
-- ------------------------------
subtype Principal is Security.Principal;
subtype Principal_Access is Security.Principal_Access;
end ASF.Principals;
|
Update to use Security.Principal
|
Update to use Security.Principal
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
b222430cae6eaf04f19cef5a9390ce232c564ea1
|
src/util-beans-objects-readers.adb
|
src/util-beans-objects-readers.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
Object_Stack.Push (Handler.Context);
Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean;
Handler.Root := To_Object (Object_Stack.Current (Handler.Context).Map, DYNAMIC);
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.Map, DYNAMIC));
else
Current.List.Append (To_Object (Next.Map, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Count, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Logger, Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
-- -----------------------
-- Get the root object.
-- -----------------------
function Get_Root (Handler : in Reader) return Object is
begin
return Handler.Root;
end Get_Root;
end Util.Beans.Objects.Readers;
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
if Current = null then
Handler.Root := To_Object (Next.Map, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.Map, DYNAMIC));
else
Current.List.Append (To_Object (Next.Map, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
if Current = null then
Handler.Root := To_Object (Next.List, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Count, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Logger, Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
-- -----------------------
-- Get the root object.
-- -----------------------
function Get_Root (Handler : in Reader) return Object is
begin
return Handler.Root;
end Get_Root;
end Util.Beans.Objects.Readers;
|
Create the root object only when the first call to Start_Object or Start_Array is made
|
Create the root object only when the first call to Start_Object or Start_Array is made
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a3cf1e2b0ea5f01ecadae18de552cc08aac2c257
|
regtests/el-objects-discrete_tests.adb
|
regtests/el-objects-discrete_tests.adb
|
-----------------------------------------------------------------------
-- el-objects-tests - Generic simple test for discrete object types
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit.Test_Caller;
with AUnit.Assertions;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
package body EL.Objects.Discrete_Tests is
use EL.Objects;
use AUnit.Assertions;
use Ada.Strings.Fixed;
procedure Test_Eq (V : String; N : Test_Type);
procedure Test_Conversion (V : String; N : Test_Type);
procedure Test_Lt_Gt (V : String; N : Test_Type);
procedure Test_Sub (V : String; N : Test_Type);
procedure Test_Add (V : String; N : Test_Type);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unreferenced (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test EL.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (V : String; N : Test_Type) is
Value : EL.Objects.Object;
begin
Value := To_Object (V);
Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test EL.Objects."+"
-- ------------------------------
procedure Test_Add (V : String; N : Test_Type) is
Value : EL.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test EL.Objects."-"
-- ------------------------------
procedure Test_Sub (V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : EL.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test EL.Objects."<" and EL.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") > 0;
begin
Res := To_Object_Test (N) < To_Object_Test (N);
Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Eq (V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Perf (V : String; N : Test_Type) is
use Ada.Calendar;
Res : Boolean;
Start : Ada.Calendar.Time;
Value : EL.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : EL.Objects.Object := Value;
begin
V := V + V;
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test EL.Objects.To_Object." & Test_Name,
Test_To_Object'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.To_String." & Test_Name,
Test_To_Object'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'='." & Test_Name,
Test_Eq'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'+'." & Test_Name,
Test_Add'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'-'." & Test_Name,
Test_Sub'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access));
Suite.Add_Test (Caller.Create ("Performance EL.Objects.'>'." & Test_Name,
Test_Perf'Access));
end Add_Tests;
end EL.Objects.Discrete_Tests;
|
-----------------------------------------------------------------------
-- el-objects-tests - Generic simple test for discrete object types
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit.Test_Caller;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
package body EL.Objects.Discrete_Tests is
use EL.Objects;
use Ada.Strings.Fixed;
procedure Test_Eq (T : Test; V : String; N : Test_Type);
procedure Test_Conversion (T : Test; V : String; N : Test_Type);
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type);
procedure Test_Sub (T : Test; V : String; N : Test_Type);
procedure Test_Add (T : Test; V : String; N : Test_Type);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (T : in Test; V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (T, V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test EL.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object;
begin
Value := To_Object (V);
T.Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
T.Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test EL.Objects."+"
-- ------------------------------
procedure Test_Add (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test EL.Objects."-"
-- ------------------------------
procedure Test_Sub (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : EL.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test EL.Objects."<" and EL.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") = V'First;
O : EL.Objects.Object := To_Object_Test (N);
begin
Res := To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O))
& " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O)));
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Eq (T : Test; V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
T.Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Perf (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (T, V);
use Ada.Calendar;
Start : Ada.Calendar.Time;
Value : constant EL.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : EL.Objects.Object := Value;
begin
V := V + V;
pragma Unreferenced (V);
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test EL.Objects.To_Object." & Test_Name,
Test_To_Object'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.To_String." & Test_Name,
Test_To_Object'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'='." & Test_Name,
Test_Eq'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'+'." & Test_Name,
Test_Add'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'-'." & Test_Name,
Test_Sub'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access));
Suite.Add_Test (Caller.Create ("Test EL.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access));
Suite.Add_Test (Caller.Create ("Performance EL.Objects.'>'." & Test_Name,
Test_Perf'Access));
end Add_Tests;
end EL.Objects.Discrete_Tests;
|
Fix compilations warnings, use new Aunit assertion methods
|
Fix compilations warnings, use new Aunit assertion methods
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
c09d3d396524ff3e5ac3ce7e419eaf2661e7668d
|
src/nanomsg-socket.adb
|
src/nanomsg-socket.adb
|
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Streams;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with Nanomsg.Sockopt;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
C.Int (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
Obj.Delete_Endpoint;
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in out Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Obj.Endpoint := Integer (C_Bind(C.Int (Obj.Fd), C_Address));
C.Strings.Free (C_Address);
if Obj.Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in out Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Obj.Endpoint := Integer (C_Connect(C.Int (Obj.Fd), C_Address));
C.Strings.Free (C_Address);
if Obj.Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
Payload : System.Address;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : out System.Address;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
function Free_Msg (Buf_Access :System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Received));
for Data'Address use Payload;
begin
Message.Set_Payload (Data);
end;
if Free_Msg (Payload) < 0 then
raise Socket_Exception with "Deallocation failed";
end if;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Ada.Streams.Stream_Element_Array;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
procedure Delete_Endpoint (Obj : in out Socket_T) is
function Nn_Shutdown (Socket : C.Int;
Endpoint : C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_shutdown";
begin
if Obj.Endpoint > 0 then
if Nn_Shutdown (C.Int (Obj.Fd), C.Int (Obj.Endpoint)) < 0 then
raise Socket_Exception with "Shutdown Error" & Nanomsg.Errors.Errno_Text;
end if;
Obj.Endpoint := -1;
end if;
end Delete_Endpoint;
function C_Setsockopt (Socket : C.Int;
Level : C.Int;
Option : C.Int;
Value : System.Address;
Size : C.Size_T) return C.Int with Import, Convention => C, External_Name => "nn_setsockopt";
procedure Set_Option (Obj : in out Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T;
Value : in Natural)
is
use Nanomsg.Sockopt;
Size : C.Size_T := C.Size_T (C.Int'Size);
begin
begin
if C_Setsockopt (C.Int (Obj.Fd),
C.Int (Level),
C.Int (Name),
Value'Address,
Size) < 0 then
raise Socket_Exception with "Setopt error";
end if;
end;
end Set_Option;
procedure Set_Option (Obj : in out Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T;
Value : in String) is
C_Value : C.Strings.Char_Array_Access := new C.Char_Array'(C.To_C (Value)) with Convention => C;
procedure Free is new Ada.Unchecked_Deallocation (Name => C.Strings.Char_Array_Access,
Object => C.Char_Array);
Size : C.Size_T := C_Value'Length;
begin
if C_Setsockopt (C.Int (Obj.Fd),
C.Int (Level),
C.Int (Name),
C_Value.all'Address,
Size) < 0 then
raise Socket_Exception with "Setopt error" & Nanomsg.Errors.Errno_Text;
end if;
Free (C_Value);
end Set_Option;
function Get_Option (Obj : in Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T) return String is
type String_Access_T is access all String;
procedure Free is new Ada.Unchecked_Deallocation (Name => String_Access_T,
Object => String);
function Nn_Getsockopt (Socket : in C.Int;
Level : in C.Int;
Option_Name : in C.Int;
Value : in out String_Access_T;
Size : in System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_getsockopt";
use Nanomsg.Sockopt;
Max_Size : constant := 63;
Ptr : String_Access_T := new String(1..Max_Size);
Size : C.Size_T := Max_Size;
use type C.Size_T;
begin
if Nn_Getsockopt (Socket => C.Int (Obj.Fd),
Level => C.Int (Level),
Option_Name => C.Int (Name),
Value => Ptr,
Size => Size'Address) < 0 then
raise Socket_Exception with "Getopt error" & Nanomsg.Errors.Errno_Text;
end if;
declare
Retval : constant String := Ptr.all(1.. Integer (Size));
begin
Free (Ptr);
return Retval;
end;
end Get_Option;
function Get_Option (Obj : in Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T) return Natural is
Retval : Natural;
Size : C.Size_T := C.Int'Size;
function Nn_Getsockopt (Socket : in C.Int;
Level : in C.Int;
Option_Name : in C.Int;
Value : in out C.Int;
Size : in System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_getsockopt";
begin
if Nn_Getsockopt (Socket => C.Int (Obj.Fd),
Level => C.Int (Level),
Option_Name => C.Int (Name),
Value => C.Int (Retval),
Size => Size'Address) < 0 then
raise Socket_Exception with "Getopt error" & Nanomsg.Errors.Errno_Text;
end if;
return Retval;
end Get_Option;
end Nanomsg.Socket;
|
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Streams;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with Nanomsg.Sockopt;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
C.Int (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
Obj.Delete_Endpoint;
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in out Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Obj.Endpoint := Integer (C_Bind(C.Int (Obj.Fd), C_Address));
C.Strings.Free (C_Address);
if Obj.Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in out Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Obj.Endpoint := Integer (C_Connect(C.Int (Obj.Fd), C_Address));
C.Strings.Free (C_Address);
if Obj.Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
Payload : System.Address;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : out System.Address;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
function Free_Msg (Buf_Access :System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Received));
for Data'Address use Payload;
begin
Message.Set_Payload (Data);
end;
if Free_Msg (Payload) < 0 then
raise Socket_Exception with "Deallocation failed";
end if;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Ada.Streams.Stream_Element_Array;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
procedure Delete_Endpoint (Obj : in out Socket_T) is
function Nn_Shutdown (Socket : C.Int;
Endpoint : C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_shutdown";
begin
if Obj.Endpoint > 0 then
if Nn_Shutdown (C.Int (Obj.Fd), C.Int (Obj.Endpoint)) < 0 then
raise Socket_Exception with "Shutdown Error" & Nanomsg.Errors.Errno_Text;
end if;
Obj.Endpoint := -1;
end if;
end Delete_Endpoint;
function C_Setsockopt (Socket : C.Int;
Level : C.Int;
Option : C.Int;
Value : System.Address;
Size : C.Size_T) return C.Int with Import, Convention => C, External_Name => "nn_setsockopt";
procedure Set_Option (Obj : in out Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T;
Value : in Natural)
is
use Nanomsg.Sockopt;
Size : C.Size_T := C.Size_T (C.Int'Size);
begin
begin
if C_Setsockopt (C.Int (Obj.Fd),
C.Int (Level),
C.Int (Name),
Value'Address,
Size) < 0 then
raise Socket_Exception with "Setopt error";
end if;
end;
end Set_Option;
procedure Set_Option (Obj : in out Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T;
Value : in String) is
C_Value : C.Strings.Char_Array_Access := new C.Char_Array'(C.To_C (Value)) with Convention => C;
procedure Free is new Ada.Unchecked_Deallocation (Name => C.Strings.Char_Array_Access,
Object => C.Char_Array);
use type C.Size_T;
Size : C.Size_T := C_Value'Length - 1;
begin
if C_Setsockopt (C.Int (Obj.Fd),
C.Int (Level),
C.Int (Name),
C_Value.all'Address,
Size) < 0 then
raise Socket_Exception with "Setopt error" & Nanomsg.Errors.Errno_Text;
end if;
Free (C_Value);
end Set_Option;
function Get_Option (Obj : in Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T) return String is
type String_Access_T is access all String;
procedure Free is new Ada.Unchecked_Deallocation (Name => String_Access_T,
Object => String);
function Nn_Getsockopt (Socket : in C.Int;
Level : in C.Int;
Option_Name : in C.Int;
Value : in out String_Access_T;
Size : in System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_getsockopt";
use Nanomsg.Sockopt;
Max_Size : constant := 63;
Ptr : String_Access_T := new String(1..Max_Size);
Size : C.Size_T := Max_Size;
use type C.Size_T;
begin
if Nn_Getsockopt (Socket => C.Int (Obj.Fd),
Level => C.Int (Level),
Option_Name => C.Int (Name),
Value => Ptr,
Size => Size'Address) < 0 then
raise Socket_Exception with "Getopt error" & Nanomsg.Errors.Errno_Text;
end if;
declare
Retval : constant String := Ptr.all(1.. Integer (Size));
begin
Free (Ptr);
return Retval;
end;
end Get_Option;
function Get_Option (Obj : in Socket_T;
Level : in Nanomsg.Sockopt.Option_Level_T;
Name : in Nanomsg.Sockopt.Option_Type_T) return Natural is
Retval : Natural;
Size : C.Size_T := C.Int'Size;
function Nn_Getsockopt (Socket : in C.Int;
Level : in C.Int;
Option_Name : in C.Int;
Value : in out C.Int;
Size : in System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_getsockopt";
begin
if Nn_Getsockopt (Socket => C.Int (Obj.Fd),
Level => C.Int (Level),
Option_Name => C.Int (Name),
Value => C.Int (Retval),
Size => Size'Address) < 0 then
raise Socket_Exception with "Getopt error" & Nanomsg.Errors.Errno_Text;
end if;
return Retval;
end Get_Option;
end Nanomsg.Socket;
|
Fix string length calculation
|
Fix string length calculation
Do not include trailing \0 into account to avoid subscription to messages
started with \0.
|
Ada
|
mit
|
landgraf/nanomsg-ada
|
9f79d7b1cd6294da323cdcd7c475d082b572512e
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : constant Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : constant Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Refactor the Properties implementation (step 2): - update the bundles implementation for the new properties implementation
|
Refactor the Properties implementation (step 2):
- update the bundles implementation for the new properties implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5ffb6aaa6fa0ed409986c88aea7576dc6c4f34a8
|
mat/src/mat-events.ads
|
mat/src/mat-events.ads
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- 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 Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is new Interfaces.Unsigned_32;
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Ptr is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : Unsigned_64;
Thid : Unsigned_32;
Thstk : Unsigned_32;
Rusage : Rusage_Info;
Cur_Depth : Unsigned_32;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- 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 Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is new Interfaces.Unsigned_32;
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Ptr is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Stack : MAT.Types.Target_Addr;
Rusage : Rusage_Info;
Cur_Depth : Natural;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
Fix the Frame_Info type
|
Fix the Frame_Info type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e3ae384ae9c602b1652cf6a0371e1464674addba
|
src/http/aws/util-http-clients-web.adb
|
src/http/aws/util-http-clients-web.adb
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with AWS.Messages;
with Util.Log.Loggers;
package body Util.Http.Clients.Web is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Get;
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data,
Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Post;
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Put {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Put;
overriding
procedure Do_Delete (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager, Http);
-- Req : constant AWS_Http_Request_Access
-- := AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Delete {0}", URI);
Reply.Delegate := Rep.all'Access;
-- Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers,
-- Timeouts => Req.Timeouts);
raise Program_Error with "Delete is not supported by AWS and there is no easy conditional"
& " compilation in Ada to enable Delete support for the latest AWS version. "
& "For now, you have to use curl, or install the latest AWS version and then "
& "uncomment the AWS.Client.Delete call and remove this exception.";
end Do_Delete;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager);
begin
AWS_Http_Request'Class (Http.Delegate.all).Timeouts
:= AWS.Client.Timeouts (Connect => Timeout,
Send => Timeout,
Receive => Timeout,
Response => Timeout);
end Set_Timeout;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
Values : constant AWS.Headers.VString_Array
:= AWS.Headers.Get_Values (Http.Headers, Name);
begin
return Values'Length > 0;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array
:= AWS.Headers.Get_Values (Request.Headers, Name);
begin
if Values'Length > 0 then
return Ada.Strings.Unbounded.To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with AWS.Messages;
with AWS.Headers.Set;
with Util.Log.Loggers;
package body Util.Http.Clients.Web is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Get;
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data,
Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Post;
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Put {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Put;
overriding
procedure Do_Delete (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager, Http);
-- Req : constant AWS_Http_Request_Access
-- := AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Delete {0}", URI);
Reply.Delegate := Rep.all'Access;
-- Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers,
-- Timeouts => Req.Timeouts);
raise Program_Error with "Delete is not supported by AWS and there is no easy conditional"
& " compilation in Ada to enable Delete support for the latest AWS version. "
& "For now, you have to use curl, or install the latest AWS version and then "
& "uncomment the AWS.Client.Delete call and remove this exception.";
end Do_Delete;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager);
begin
AWS_Http_Request'Class (Http.Delegate.all).Timeouts
:= AWS.Client.Timeouts (Connect => Timeout,
Send => Timeout,
Receive => Timeout,
Response => Timeout);
end Set_Timeout;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
Values : constant AWS.Headers.VString_Array
:= AWS.Headers.Get_Values (Http.Headers, Name);
begin
return Values'Length > 0;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array
:= AWS.Headers.Get_Values (Request.Headers, Name);
begin
if Values'Length > 0 then
return Ada.Strings.Unbounded.To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
Revert previous commit and use AWS.Headers.Set package because it becomes no longer possible to build Ada Util on Ubuntu 16.04 because it is based on an AWS version that does not provide the Add procedure in the AWS.Headers package. Building a recent AWS version with Ubuntu 16.04 Ada compiler is not possible as the compiler (gcc 4.9) crashes.
|
Revert previous commit and use AWS.Headers.Set package because it
becomes no longer possible to build Ada Util on Ubuntu 16.04 because
it is based on an AWS version that does not provide the Add procedure
in the AWS.Headers package. Building a recent AWS version with Ubuntu
16.04 Ada compiler is not possible as the compiler (gcc 4.9) crashes.
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8ed8ee3573b548bb2ba9728532a3a61e40d26df9
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- == Documents ==
-- The `Document` type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The `Document` holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the `Wiki.Documents` package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
--
-- After parsing some HTML or Wiki text, it will contain a representation of the
-- HTML or Wiki text. It is possible to populate the document by using one of
-- the `Append`, `Add_Link`, `Add_Image` operation.
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a definition item at end of the document.
procedure Add_Definition (Into : in out Document;
Definition : in Wiki.Strings.WString);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list (<ul> or <ol>) starting at the given number.
procedure Add_List (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Into : in out Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Into : in out Document);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref;
-- Set a link definition.
procedure Set_Link (Doc : in out Document;
Name : in Wiki.Strings.WString;
Link : in Wiki.Strings.WString);
-- Get a link definition.
function Get_Link (Doc : in out Document;
Name : in Wiki.Strings.WString) return Wiki.Strings.WString;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Links : Wiki.Strings.Maps.Map;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- == Documents ==
-- The `Document` type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The `Document` holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the `Wiki.Documents` package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
--
-- After parsing some HTML or Wiki text, it will contain a representation of the
-- HTML or Wiki text. It is possible to populate the document by using one of
-- the `Append`, `Add_Link`, `Add_Image` operation.
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
procedure Start_Block (Into : in out Document;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Natural);
procedure End_Block (From : in out Document;
Kind : in Wiki.Nodes.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);
-- Add a definition item at end of the document.
procedure Add_Definition (Into : in out Document;
Definition : in Wiki.Strings.WString);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a link reference with the given label.
procedure Add_Link_Ref (Into : in out Document;
Label : in Wiki.Strings.WString);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list (<ul> or <ol>) starting at the given number.
procedure Add_List (Into : in out Document;
Level : in Natural;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Into : in out Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Into : in out Document);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref;
-- Set a link definition.
procedure Set_Link (Doc : in out Document;
Name : in Wiki.Strings.WString;
Link : in Wiki.Strings.WString;
Title : in Wiki.Strings.WString);
-- Get a link definition.
function Get_Link (Doc : in Document;
Label : in Wiki.Strings.WString) return Wiki.Strings.WString;
function Get_Link_Title (Doc : in Document;
Label : in Wiki.Strings.WString) return Wiki.Strings.WString;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Links : Wiki.Strings.Maps.Map;
Titles : Wiki.Strings.Maps.Map;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Add Start_Block, End_Block, Add_Link_Ref, Get_Link_Title
|
Add Start_Block, End_Block, Add_Link_Ref, Get_Link_Title
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f7a2fd94ac26ceefc6eb680abfdd47cc1755f018
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.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);
-- 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;
-- 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;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.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);
-- 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;
-- 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;
end record;
end Wiki.Documents;
|
Declare Is_Using_TOC function Add a Using_TOC member to the document to track the use of __TOC__
|
Declare Is_Using_TOC function
Add a Using_TOC member to the document to track the use of __TOC__
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
32f4334db51db72cc6e39898be1175feccdb2876
|
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;
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;
|
-----------------------------------------------------------------------
-- 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;
Sql_Type_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 support for the sql type name tag definition
|
Add support for the sql type name tag definition
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
31f73d28afa8e68376595b226f4fe91ef5078929
|
src/ado-queries.adb
|
src/ado-queries.adb
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- 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 ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Driver : in ADO.Drivers.Driver_Index) return String is
begin
if From.Query_Def = null then
return "";
else
return Get_SQL (From.Query_Def, Driver, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Driver : in ADO.Drivers.Driver_Index;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (From);
Query := From.Query.Get;
if Query.Is_Null then
return "";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Driver).SQL);
else
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
elsif Length (Query.Value.Main_Query (Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Driver).SQL);
else
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
end Get_SQL;
end ADO.Queries;
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the query to execute as SQL statement.
-- ------------------------------
procedure Set_SQL (Into : in out Context;
SQL : in String) is
begin
ADO.SQL.Clear (Into.SQL);
ADO.SQL.Append (Into.SQL, SQL);
end Set_SQL;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Driver : in ADO.Drivers.Driver_Index) return String is
begin
if From.Query_Def = null then
return ADO.SQL.To_String (From.SQL);
else
return Get_SQL (From.Query_Def, Driver, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Driver : in ADO.Drivers.Driver_Index;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (From);
Query := From.Query.Get;
if Query.Is_Null then
return "";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Driver).SQL);
else
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
elsif Length (Query.Value.Main_Query (Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Driver).SQL);
else
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
end Get_SQL;
end ADO.Queries;
|
Implement the Set_SQL procedure to setup the SQL query with a SQL string
|
Implement the Set_SQL procedure to setup the SQL query with a SQL string
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
e4cd6f97c3fa86a585f8d2fc01dcbf4be7a8f885
|
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 := "06";
copyright_years : constant String := "2015-2018";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "07";
copyright_years : constant String := "2015-2018";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
Bump version for today's changes
|
Bump version for today's changes
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
5d85fc08ad431ba96cbdda4ed65fc302e1f6c83d
|
mat/src/mat-consoles-text.adb
|
mat/src/mat-consoles-text.adb
|
-----------------------------------------------------------------------
-- mat-consoles-text - Text console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles.Text is
-- ------------------------------
-- Print the field value for the given field.
-- ------------------------------
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Value'Length);
end if;
Ada.Text_IO.Put (Value);
end Print_Field;
-- ------------------------------
-- Print the title for the given field.
-- ------------------------------
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length);
end if;
Ada.Text_IO.Put (Title);
end Print_Title;
-- ------------------------------
-- Start a new title in a report.
-- ------------------------------
overriding
procedure Start_Title (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
Console.Sizes := (others => 0);
Console.Cols := (others => 1);
end Start_Title;
-- ------------------------------
-- Finish a new title in a report.
-- ------------------------------
procedure End_Title (Console : in out Console_Type) is
begin
Ada.Text_IO.New_Line;
end End_Title;
-- ------------------------------
-- Start a new row in a report.
-- ------------------------------
overriding
procedure Start_Row (Console : in out Console_Type) is
begin
null;
end Start_Row;
-- ------------------------------
-- Finish a new row in a report.
-- ------------------------------
overriding
procedure End_Row (Console : in out Console_Type) is
begin
Ada.Text_IO.New_Line;
end End_Row;
end MAT.Consoles.Text;
|
-----------------------------------------------------------------------
-- mat-consoles-text - Text console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles.Text is
-- ------------------------------
-- Report an error message.
-- ------------------------------
overriding
procedure Error (Console : in out Console_Type;
Message : in String) is
begin
Ada.Text_IO.Put_Line (Message);
end Error;
-- ------------------------------
-- Print the field value for the given field.
-- ------------------------------
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Value'Length);
end if;
Ada.Text_IO.Put (Value);
end Print_Field;
-- ------------------------------
-- Print the title for the given field.
-- ------------------------------
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length);
end if;
Ada.Text_IO.Put (Title);
end Print_Title;
-- ------------------------------
-- Start a new title in a report.
-- ------------------------------
overriding
procedure Start_Title (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
Console.Sizes := (others => 0);
Console.Cols := (others => 1);
end Start_Title;
-- ------------------------------
-- Finish a new title in a report.
-- ------------------------------
procedure End_Title (Console : in out Console_Type) is
begin
Ada.Text_IO.New_Line;
end End_Title;
-- ------------------------------
-- Start a new row in a report.
-- ------------------------------
overriding
procedure Start_Row (Console : in out Console_Type) is
begin
null;
end Start_Row;
-- ------------------------------
-- Finish a new row in a report.
-- ------------------------------
overriding
procedure End_Row (Console : in out Console_Type) is
begin
Ada.Text_IO.New_Line;
end End_Row;
end MAT.Consoles.Text;
|
Implement the Error procedure
|
Implement the Error procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
444d5753ef4c9e0e745892cca2ea45446590ee65
|
awa/awaunit/awa-tests-helpers-users.ads
|
awa/awaunit/awa-tests-helpers-users.ads
|
-----------------------------------------------------------------------
-- users-tests-helpers -- Helpers for user creation
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Security.Contexts;
with ASF.Requests.Mockup;
with AWA.Users.Models;
with AWA.Users.Services;
with AWA.Services.Contexts;
with AWA.Users.Principals;
package AWA.Tests.Helpers.Users is
type Test_User is new Ada.Finalization.Limited_Controlled with record
Context : AWA.Services.Contexts.Service_Context;
Manager : AWA.Users.Services.User_Service_Access := null;
User : AWA.Users.Models.User_Ref;
Email : AWA.Users.Models.Email_Ref;
Session : AWA.Users.Models.Session_Ref;
Principal : AWA.Users.Principals.Principal_Access;
end record;
-- Initialize the service context.
procedure Initialize (Principal : in out Test_User);
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
procedure Create_User (Principal : in out Test_User;
Email : in String);
-- Create a test user for a new test and get an open session.
procedure Create_User (Principal : in out Test_User);
-- Find the access key associated with a user (if any).
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref);
-- Login a user and create a session
procedure Login (Principal : in out Test_User);
-- Logout the user and closes the current session.
procedure Logout (Principal : in out Test_User);
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String);
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request);
-- Setup the context and security context to simulate an anonymous user.
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context);
-- Simulate the recovery password process for the given user.
procedure Recover_Password (Email : in String);
overriding
procedure Finalize (Principal : in out Test_User);
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
procedure Tear_Down;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- users-tests-helpers -- Helpers for user creation
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Security.Contexts;
with ASF.Requests.Mockup;
with AWA.Users.Models;
with AWA.Users.Services;
with AWA.Services.Contexts;
with AWA.Users.Principals;
package AWA.Tests.Helpers.Users is
type Test_User is new Ada.Finalization.Limited_Controlled with record
Context : AWA.Services.Contexts.Service_Context;
Manager : AWA.Users.Services.User_Service_Access := null;
User : AWA.Users.Models.User_Ref;
Email : AWA.Users.Models.Email_Ref;
Session : AWA.Users.Models.Session_Ref;
Principal : AWA.Users.Principals.Principal_Access;
end record;
-- Initialize the service context.
procedure Initialize (Principal : in out Test_User);
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
procedure Create_User (Principal : in out Test_User;
Email : in String);
-- Create a test user for a new test and get an open session.
procedure Create_User (Principal : in out Test_User);
-- Find the access key associated with a user (if any).
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref);
-- Login a user and create a session
procedure Login (Principal : in out Test_User);
-- Logout the user and closes the current session.
procedure Logout (Principal : in out Test_User);
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String);
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request'Class);
-- Setup the context and security context to simulate an anonymous user.
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context);
-- Simulate the recovery password process for the given user.
procedure Recover_Password (Email : in String);
overriding
procedure Finalize (Principal : in out Test_User);
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
procedure Tear_Down;
end AWA.Tests.Helpers.Users;
|
Update to allow class wide request for Login
|
Update to allow class wide request for Login
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
25aca5254eb4bf583810ddc387493a86b63f0738
|
mat/src/events/mat-events-probes.ads
|
mat/src/events/mat-events-probes.ads
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type;
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Probe_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in Probe_Event_Type) is abstract;
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Internal_Reference;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
Events : MAT.Events.Targets.Target_Events_Access;
Event : Probe_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type;
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Probe_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in Probe_Event_Type) is abstract;
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Get the target events.
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access;
-- Read a message from the stream.
procedure Read_Message (Reader : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is abstract;
type Reader_List_Type is limited interface;
type Reader_List_Type_Access is access all Reader_List_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (List : in out Reader_List_Type;
Manager : in out Probe_Manager_Type'Class) is abstract;
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Targets.Probe_Index_Type;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
Events : MAT.Events.Targets.Target_Events_Access;
Event : Probe_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
Define the Reader_List_Type interface
|
Define the Reader_List_Type interface
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e8c17a4cd2f1945cf607865d9cd45fda8a8226f5
|
mat/src/matp.adb
|
mat/src/matp.adb
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Readers.Streams.Sockets;
procedure Matp is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
begin
Target.Console (Console'Unchecked_Access);
Target.Initialize_Options;
MAT.Commands.Initialize_Files (Target);
Target.Start;
MAT.Commands.Interactive (Target);
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error =>
Server.Stop;
end Matp;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
procedure Matp is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
begin
Target.Console (Console'Unchecked_Access);
Target.Initialize_Options;
MAT.Commands.Initialize_Files (Target);
Target.Start;
MAT.Commands.Interactive (Target);
Target.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error =>
Target.Stop;
end Matp;
|
Use the MAT.Targets.Stop operation
|
Use the MAT.Targets.Stop operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3c04b93f574089eadb1e57843045167fc9603a09
|
src/wiki-render.adb
|
src/wiki-render.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Render is
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
pragma Unreferenced (Renderer);
begin
URI := Link;
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
pragma Unreferenced (Renderer);
begin
URI := Link;
Exists := True;
end Make_Page_Link;
-- ------------------------------
-- Render the list of nodes from the document.
-- ------------------------------
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document;
List : in Wiki.Nodes.Node_List_Access) is
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
Wiki.Nodes.Iterate (List, Process'Access);
end Render;
end Wiki.Render;
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Render is
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
pragma Unreferenced (Renderer);
begin
URI := Link;
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
pragma Unreferenced (Renderer);
begin
URI := To_Unbounded_Wide_Wide_String (Link);
Exists := True;
end Make_Page_Link;
-- ------------------------------
-- Render the list of nodes from the document.
-- ------------------------------
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document;
List : in Wiki.Nodes.Node_List_Access) is
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
Wiki.Nodes.Iterate (List, Process'Access);
end Render;
-- ------------------------------
-- Render the document.
-- ------------------------------
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Nodes.Document) is
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
Wiki.Nodes.Iterate (Doc, Process'Access);
end Render;
end Wiki.Render;
|
Implement the Render procedure on a Document
|
Implement the Render procedure on a Document
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
65718225a8939eb9987910b5b1e35820dfc86c39
|
src/wiki-helpers.adb
|
src/wiki-helpers.adb
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the character is a line terminator.
-- ------------------------------
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wiki.Strings.WString) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is
S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
-- ------------------------------
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural) is
Pos : Natural;
Last : Natural;
begin
if Dimension = "original" then
Width := Natural'Last;
Height := Natural'Last;
elsif Dimension = "default" or Dimension = "upright" then
Width := 800;
Height := 0;
else
Pos := Wiki.Strings.Index (Dimension, "x");
Last := Wiki.Strings.Index (Dimension, "px");
if Pos > Dimension'First and Last + 1 /= Pos then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1));
elsif Last > 0 then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1));
else
Width := 0;
end if;
if Pos < Dimension'Last then
Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1));
else
Height := 0;
end if;
end if;
exception
when Constraint_Error =>
Width := 0;
Height := 0;
end Get_Sizes;
end Wiki.Helpers;
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the character is a line terminator.
-- ------------------------------
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wiki.Strings.WString) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is
S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
-- ------------------------------
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural) is
Pos : Natural;
Last : Natural;
begin
if Dimension = "original" then
Width := Natural'Last;
Height := Natural'Last;
elsif Dimension = "default" or Dimension = "upright" then
Width := 800;
Height := 0;
else
Pos := Wiki.Strings.Index (Dimension, "x");
Last := Wiki.Strings.Index (Dimension, "px");
if Pos > Dimension'First and Last + 1 /= Pos then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1));
elsif Last > 0 then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1));
else
Width := 0;
end if;
if Pos < Dimension'Last then
Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1));
else
Height := 0;
end if;
end if;
exception
when Constraint_Error =>
Width := 0;
Height := 0;
end Get_Sizes;
end Wiki.Helpers;
|
Update Is_Space so that the is treated as a space
|
Update Is_Space so that the is treated as a space
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6230de418f506325b69027d8029a3a669882ca01
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
end Test_Parser;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
end Test_Parser;
end Util.Serialize.IO.JSON.Tests;
|
Add a test case for json
|
Add a test case for json
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b1ec989a29d149293ea518b1845d624228129c20
|
awa/src/awa-wikis-documents.ads
|
awa/src/awa-wikis-documents.ads
|
-----------------------------------------------------------------------
-- awa-wikis-documents -- Wiki module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package AWA.Wikis.Documents is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- ------------------------------
-- Document reader
-- ------------------------------
type Document_Reader is limited interface;
type Document_Reader_Access is access all Document_Reader'Class;
-- Add a section header in the document.
procedure Add_Header (Document : in out Document_Reader;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is abstract;
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Document_Reader) is abstract;
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Document : in out Document_Reader) is abstract;
-- 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 (Document : in out Document_Reader;
Level : in Positive;
Ordered : in Boolean) is abstract;
-- Add an horizontal rule (<hr>).
procedure Add_Horizontal_Rule (Document : in out Document_Reader) is abstract;
-- Add a link.
procedure Add_Link (Document : in out Document_Reader;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is abstract;
-- Add an image.
procedure Add_Image (Document : in out Document_Reader;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is abstract;
-- Add a quote.
procedure Add_Quote (Document : in out Document_Reader;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is abstract;
-- Add a text block with the given format.
procedure Add_Text (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Format_Map) is abstract;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is abstract;
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Document_Reader) is abstract;
end AWA.Wikis.Documents;
|
-----------------------------------------------------------------------
-- awa-wikis-documents -- Wiki module
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package AWA.Wikis.Documents is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- ------------------------------
-- Document reader
-- ------------------------------
type Document_Reader is limited interface;
type Document_Reader_Access is access all Document_Reader'Class;
-- Add a section header in the document.
procedure Add_Header (Document : in out Document_Reader;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is abstract;
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Document_Reader) is abstract;
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Document : in out Document_Reader) is abstract;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Document_Reader;
Level : in Natural) is abstract;
-- 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 (Document : in out Document_Reader;
Level : in Positive;
Ordered : in Boolean) is abstract;
-- Add an horizontal rule (<hr>).
procedure Add_Horizontal_Rule (Document : in out Document_Reader) is abstract;
-- Add a link.
procedure Add_Link (Document : in out Document_Reader;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is abstract;
-- Add an image.
procedure Add_Image (Document : in out Document_Reader;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is abstract;
-- Add a quote.
procedure Add_Quote (Document : in out Document_Reader;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is abstract;
-- Add a text block with the given format.
procedure Add_Text (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Format_Map) is abstract;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is abstract;
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Document_Reader) is abstract;
end AWA.Wikis.Documents;
|
Declare the Add_Blockquote procedure
|
Declare the Add_Blockquote procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5b6941f8d7018ad9b9311c2548a4569585359f57
|
regtests/util-beans-objects-discrete_tests.adb
|
regtests/util-beans-objects-discrete_tests.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
with Util.Test_Caller;
with Util.Beans.Objects.Hash;
package body Util.Beans.Objects.Discrete_Tests is
use Ada.Strings.Fixed;
use Ada.Containers;
use Util.Tests;
procedure Test_Eq (T : Test; V : String; N : Test_Type);
procedure Test_Conversion (T : Test; V : String; N : Test_Type);
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type);
procedure Test_Sub (T : Test; V : String; N : Test_Type);
procedure Test_Add (T : Test; V : String; N : Test_Type);
procedure Test_Perf (T : Test; V : String; N : Test_Type);
procedure Test_Hash (T : in out Test);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (T : in Test; V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (T, V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test Util.Beans.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (T : Test; V : String; N : Test_Type) is
Value : Util.Beans.Objects.Object;
begin
Value := To_Object (V);
T.Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
T.Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test Util.Beans.Objects.Hash
-- ------------------------------
procedure Test_Hash (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0);
Nb_Hash : Natural := 0;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
Value : constant Util.Beans.Objects.Object := To_Object_Test (N);
H : constant Hash_Type := Util.Beans.Objects.Hash (Value);
Found : Boolean := False;
begin
for J in 1 .. Nb_Hash loop
if Hash_Values (J) = H then
Found := True;
end if;
end loop;
if not Found then
Nb_Hash := Nb_Hash + 1;
Hash_Values (Nb_Hash) := H;
end if;
end;
Pos := Next + 1;
end loop;
Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values");
T.Assert (Nb_Hash > 1, "Only one hash value found");
end Test_Hash;
-- ------------------------------
-- Test Util.Beans.Objects."+"
-- ------------------------------
procedure Test_Add (T : Test; V : String; N : Test_Type) is
Value : Util.Beans.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test Util.Beans.Objects."-"
-- ------------------------------
procedure Test_Sub (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : Util.Beans.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test Util.Beans.Objects."<" and Util.Beans.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") = V'First;
O : constant Util.Beans.Objects.Object := To_Object_Test (N);
begin
Res := To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O))
& " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O)));
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test Util.Beans.Objects."="
-- ------------------------------
procedure Test_Eq (T : Test; V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
T.Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test Util.Beans.Objects."="
-- ------------------------------
procedure Test_Perf (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (T, V);
use Ada.Calendar;
Start : Ada.Calendar.Time;
Value : constant Util.Beans.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : Util.Beans.Objects.Object := Value;
begin
V := V + V;
pragma Unreferenced (V);
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new Util.Test_Caller (Test, "Objects." & Test_Name);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name,
Test_Eq'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name,
Test_Add'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name,
Test_Sub'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name,
Test_Perf'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name,
Test_Hash'Access);
end Add_Tests;
end Util.Beans.Objects.Discrete_Tests;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types
-- Copyright (C) 2009, 2010, 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.Containers;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
with Util.Test_Caller;
with Util.Beans.Objects.Hash;
package body Util.Beans.Objects.Discrete_Tests is
use Ada.Strings.Fixed;
use Ada.Containers;
procedure Test_Eq (T : Test; V : String; N : Test_Type);
procedure Test_Conversion (T : Test; V : String; N : Test_Type);
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type);
procedure Test_Sub (T : Test; V : String; N : Test_Type);
procedure Test_Add (T : Test; V : String; N : Test_Type);
procedure Test_Perf (T : Test; V : String; N : Test_Type);
procedure Test_Hash (T : in out Test);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (T : in Test; V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (T, V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test Util.Beans.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (T : Test; V : String; N : Test_Type) is
Value : Util.Beans.Objects.Object;
begin
Value := To_Object (V);
T.Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
T.Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test Util.Beans.Objects.Hash
-- ------------------------------
procedure Test_Hash (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0);
Nb_Hash : Natural := 0;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
Value : constant Util.Beans.Objects.Object := To_Object_Test (N);
H : constant Hash_Type := Util.Beans.Objects.Hash (Value);
Found : Boolean := False;
begin
for J in 1 .. Nb_Hash loop
if Hash_Values (J) = H then
Found := True;
end if;
end loop;
if not Found then
Nb_Hash := Nb_Hash + 1;
Hash_Values (Nb_Hash) := H;
end if;
end;
Pos := Next + 1;
end loop;
Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values");
T.Assert (Nb_Hash > 1, "Only one hash value found");
end Test_Hash;
-- ------------------------------
-- Test Util.Beans.Objects."+"
-- ------------------------------
procedure Test_Add (T : Test; V : String; N : Test_Type) is
Value : Util.Beans.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test Util.Beans.Objects."-"
-- ------------------------------
procedure Test_Sub (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : Util.Beans.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test Util.Beans.Objects."<" and Util.Beans.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") = V'First;
O : constant Util.Beans.Objects.Object := To_Object_Test (N);
begin
Res := To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O))
& " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O)));
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test Util.Beans.Objects."="
-- ------------------------------
procedure Test_Eq (T : Test; V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
T.Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test Util.Beans.Objects."="
-- ------------------------------
procedure Test_Perf (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (T, V);
use Ada.Calendar;
Start : Ada.Calendar.Time;
Value : constant Util.Beans.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : Util.Beans.Objects.Object := Value;
begin
V := V + V;
pragma Unreferenced (V);
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new Util.Test_Caller (Test, "Objects." & Test_Name);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name,
Test_Eq'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name,
Test_Add'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name,
Test_Sub'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name,
Test_Perf'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name,
Test_Hash'Access);
end Add_Tests;
end Util.Beans.Objects.Discrete_Tests;
|
Remove unused use Util.Tests clause
|
Remove unused use Util.Tests clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a4a9d004899e82b5f8d10085819ca84fa5906e2b
|
boards/MicroBit/src/microbit.ads
|
boards/MicroBit/src/microbit.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package MicroBit is
end MicroBit;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.Device;
with nRF51.GPIO;
package MicroBit is
MB_P0 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P03; -- 0 pad on edge connector
MB_P1 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P02; -- 1 pad on edge connector
MB_P2 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P01; -- 2 pad on edge connector
MB_P3 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P04; -- Display column 1
MB_P4 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P05; -- Display column 2
MB_P5 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P17; -- Button A
MB_P6 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P12; -- Display column 9
MB_P7 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P11; -- Display column 8
MB_P8 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P18;
MB_P9 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P10; -- Display column 7
MB_P10 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P06; -- Display column 3
MB_P11 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P26; -- Button B
MB_P12 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P20;
MB_P13 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P23; -- SCK
MB_P14 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P22; -- MISO
MB_P15 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P21; -- MOSI
MB_P16 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P16;
MB_P19 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P00; -- SCL
MB_P20 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P30; -- SDA
end MicroBit;
|
Define MicroBit pins
|
MicroBit: Define MicroBit pins
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
a5443b84c8535c0275e69893b5a506b4befd6d58
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans.Factories;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => AWA.Storages.Models.DATABASE);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (Data.Is_Null, "A non null blob returned by load");
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Factories.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Folder2 : AWA.Storages.Beans.Factories.Folder_Bean;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Set_Name ("Test folder name");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
Folder2.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key));
Util.Tests.Assert_Equals (T, "Test folder name", String '(Folder2.Get_Name),
"Invalid folder name");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans.Factories;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => AWA.Storages.Models.DATABASE);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
begin
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (False, "No exception raised");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Factories.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Upload : AWA.Storages.Beans.Factories.Upload_Bean;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Upload.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Test folder name");
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key));
Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name),
"Invalid folder name");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
Fix storage unit test
|
Fix storage unit test
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
40ea7522e9fcdabfed12928f1c2871c42ccbf49b
|
src/port_specification-json.adb
|
src/port_specification-json.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Utilities;
with Ada.Characters.Latin_1;
package body Port_Specification.Json is
package UTL renames Utilities;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- describe_port
--------------------------------------------------------------------------------------------
procedure describe_port
(specs : Portspecs;
dossier : TIO.File_Type;
bucket : String;
index : Positive)
is
fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port);
nvar : constant Natural := specs.get_number_of_variants;
begin
TIO.Put
(dossier,
UTL.json_object (True, 3, index) &
UTL.json_nvpair_string ("bucket", bucket, 1, pad) &
UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) &
UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) &
homepage_line (specs) &
UTL.json_nvpair_string ("FPC", fpcval, 3, pad) &
UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) &
UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) &
specs.get_json_contacts &
describe_Common_Platform_Enumeration (specs) &
UTL.json_name_complex ("variants", 4, pad) &
UTL.json_array (True, pad + 1)
);
for x in 1 .. nvar loop
declare
varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x);
sdesc : constant String := escape_tagline (specs.get_tagline (varstr));
spray : constant String := describe_subpackages (specs, varstr);
begin
TIO.Put
(dossier,
UTL.json_object (True, pad + 2, x) &
UTL.json_nvpair_string ("label", varstr, 1, pad + 3) &
UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) &
UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) &
UTL.json_object (False, pad + 2, x)
);
end;
end loop;
TIO.Put
(dossier,
UTL.json_array (False, pad + 1) &
UTL.json_object (False, 3, index)
);
end describe_port;
--------------------------------------------------------------------------------------------
-- fpc_value
--------------------------------------------------------------------------------------------
function fpc_value (is_generated : Boolean; raw_value : String) return String is
begin
if is_generated then
return "generated";
else
return raw_value;
end if;
end fpc_value;
--------------------------------------------------------------------------------------------
-- describe_keywords
--------------------------------------------------------------------------------------------
function describe_keywords (specs : Portspecs) return String
is
raw : constant String := specs.get_field_value (Port_Specification.sp_keywords);
innerquote : constant String :=
HT.replace_char
(S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma),
focus => LAT.Space,
substring => LAT.Space & LAT.Quotation);
begin
return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]";
end describe_keywords;
--------------------------------------------------------------------------------------------
-- describe_distfiles
--------------------------------------------------------------------------------------------
function describe_distfiles (specs : Portspecs) return String
is
numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numfiles loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_distfiles;
--------------------------------------------------------------------------------------------
-- describe_subpackages
--------------------------------------------------------------------------------------------
function describe_subpackages (specs : Portspecs; variant : String) return String
is
numpkg : constant Natural := specs.get_subpackage_length (variant);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numpkg loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation &
specs.get_subpackage_item (variant, x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_subpackages;
--------------------------------------------------------------------------------------------
-- escape_tagline
--------------------------------------------------------------------------------------------
function escape_tagline (raw : String) return String
is
focus : constant String :=
LAT.Reverse_Solidus &
LAT.Quotation &
LAT.Solidus &
LAT.BS &
LAT.FF &
LAT.LF &
LAT.CR &
LAT.HT;
curlen : Natural := raw'Length;
result : String (1 .. raw'Length * 2) := (others => ' ');
begin
result (1 .. curlen) := raw;
for x in focus'Range loop
if HT.count_char (result (1 .. curlen), focus (x)) > 0 then
declare
newstr : String := HT.replace_char (result (1 .. curlen), focus (x),
LAT.Reverse_Solidus & focus (x));
begin
curlen := newstr'Length;
result (1 .. curlen) := newstr;
end;
end if;
end loop;
return result (1 .. curlen);
end escape_tagline;
--------------------------------------------------------------------------------------------
-- homepage_line
--------------------------------------------------------------------------------------------
function homepage_line (specs : Portspecs) return String
is
homepage : constant String := specs.get_field_value (sp_homepage);
begin
if homepage = homepage_none or else
specs.repology_sucks
then
return "";
end if;
return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad);
end homepage_line;
--------------------------------------------------------------------------------------------
-- describe_Common_Platform_Enumeration
--------------------------------------------------------------------------------------------
function describe_Common_Platform_Enumeration (specs : Portspecs) return String
is
function retrieve (key : String; default_value : String) return String;
function form_object (product, vendor : String) return String;
function retrieve (key : String; default_value : String) return String
is
key_text : HT.Text := HT.SUS (key);
begin
if specs.catch_all.Contains (key_text) then
return HT.USS (specs.catch_all.Element (key_text).list.First_Element);
else
return default_value;
end if;
end retrieve;
function form_object (product, vendor : String) return String
is
data1 : String := UTL.json_nvpair_string ("product", product, 1, 0); -- trailing LF
data2 : String := UTL.json_nvpair_string ("vendor", vendor, 1, 0); -- trailing LF
begin
return "{ " & data1 (data1'First .. data1'Last - 1) & ", "
& data2 (data2'First .. data2'Last - 1) & "}";
end form_object;
begin
if not specs.uses.Contains (HT.SUS ("cpe")) then
return "";
end if;
declare
cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase));
cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product);
begin
return UTL.json_nvpair_complex ("cpe", form_object (cpe_product, cpe_vendor), 3, pad);
end;
end describe_Common_Platform_Enumeration;
end Port_Specification.Json;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Utilities;
with Ada.Characters.Latin_1;
package body Port_Specification.Json is
package UTL renames Utilities;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- describe_port
--------------------------------------------------------------------------------------------
procedure describe_port
(specs : Portspecs;
dossier : TIO.File_Type;
bucket : String;
index : Positive)
is
fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port);
nvar : constant Natural := specs.get_number_of_variants;
begin
TIO.Put
(dossier,
UTL.json_object (True, 3, index) &
UTL.json_nvpair_string ("bucket", bucket, 1, pad) &
UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) &
UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) &
homepage_line (specs) &
UTL.json_nvpair_string ("FPC", fpcval, 3, pad) &
UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) &
UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) &
specs.get_json_contacts &
describe_Common_Platform_Enumeration (specs) &
UTL.json_name_complex ("variants", 4, pad) &
UTL.json_array (True, pad + 1)
);
for x in 1 .. nvar loop
declare
varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x);
sdesc : constant String := escape_tagline (specs.get_tagline (varstr));
spray : constant String := describe_subpackages (specs, varstr);
begin
TIO.Put
(dossier,
UTL.json_object (True, pad + 2, x) &
UTL.json_nvpair_string ("label", varstr, 1, pad + 3) &
UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) &
UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) &
UTL.json_object (False, pad + 2, x)
);
end;
end loop;
TIO.Put
(dossier,
UTL.json_array (False, pad + 1) &
UTL.json_object (False, 3, index)
);
end describe_port;
--------------------------------------------------------------------------------------------
-- fpc_value
--------------------------------------------------------------------------------------------
function fpc_value (is_generated : Boolean; raw_value : String) return String is
begin
if is_generated then
return "generated";
else
return raw_value;
end if;
end fpc_value;
--------------------------------------------------------------------------------------------
-- describe_keywords
--------------------------------------------------------------------------------------------
function describe_keywords (specs : Portspecs) return String
is
raw : constant String := specs.get_field_value (Port_Specification.sp_keywords);
innerquote : constant String :=
HT.replace_char
(S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma),
focus => LAT.Space,
substring => LAT.Space & LAT.Quotation);
begin
return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]";
end describe_keywords;
--------------------------------------------------------------------------------------------
-- describe_distfiles
--------------------------------------------------------------------------------------------
function describe_distfiles (specs : Portspecs) return String
is
numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numfiles loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_distfiles;
--------------------------------------------------------------------------------------------
-- describe_subpackages
--------------------------------------------------------------------------------------------
function describe_subpackages (specs : Portspecs; variant : String) return String
is
numpkg : constant Natural := specs.get_subpackage_length (variant);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numpkg loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation &
specs.get_subpackage_item (variant, x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_subpackages;
--------------------------------------------------------------------------------------------
-- escape_tagline
--------------------------------------------------------------------------------------------
function escape_tagline (raw : String) return String
is
focus : constant String :=
LAT.Reverse_Solidus &
LAT.Quotation &
LAT.Solidus &
LAT.BS &
LAT.FF &
LAT.LF &
LAT.CR &
LAT.HT;
curlen : Natural := raw'Length;
result : String (1 .. raw'Length * 2) := (others => ' ');
begin
result (1 .. curlen) := raw;
for x in focus'Range loop
if HT.count_char (result (1 .. curlen), focus (x)) > 0 then
declare
newstr : String := HT.replace_char (result (1 .. curlen), focus (x),
LAT.Reverse_Solidus & focus (x));
begin
curlen := newstr'Length;
result (1 .. curlen) := newstr;
end;
end if;
end loop;
return result (1 .. curlen);
end escape_tagline;
--------------------------------------------------------------------------------------------
-- homepage_line
--------------------------------------------------------------------------------------------
function homepage_line (specs : Portspecs) return String
is
homepage : constant String := specs.get_field_value (sp_homepage);
begin
if homepage = homepage_none or else
specs.repology_sucks
then
return "";
end if;
return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad);
end homepage_line;
--------------------------------------------------------------------------------------------
-- describe_Common_Platform_Enumeration
--------------------------------------------------------------------------------------------
function describe_Common_Platform_Enumeration (specs : Portspecs) return String
is
function retrieve (key : String; default_value : String) return String;
function form_object (product, vendor : String) return String;
function retrieve (key : String; default_value : String) return String
is
key_text : HT.Text := HT.SUS (key);
begin
if specs.catch_all.Contains (key_text) then
return HT.USS (specs.catch_all.Element (key_text).list.First_Element);
else
return default_value;
end if;
end retrieve;
function form_object (product, vendor : String) return String
is
data1 : String := UTL.json_nvpair_string ("product", product, 1, 0); -- trailing LF
data2 : String := UTL.json_nvpair_string ("vendor", vendor, 1, 0); -- trailing LF
begin
return "{" & data1 (data1'First .. data1'Last - 1) & LAT.Comma
& data2 (data2'First .. data2'Last - 1) & " }";
end form_object;
begin
if not specs.uses.Contains (HT.SUS ("cpe")) then
return "";
end if;
declare
cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase));
cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product);
begin
return UTL.json_nvpair_complex ("cpe", form_object (cpe_product, cpe_vendor), 3, pad);
end;
end describe_Common_Platform_Enumeration;
end Port_Specification.Json;
|
Fix spacing on cpe json
|
Fix spacing on cpe json
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
9948a0aa74c1cdd260e5c41e91f58a56ddc610ae
|
src/drivers/adabase-driver-base-postgresql.adb
|
src/drivers/adabase-driver-base-postgresql.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
package body AdaBase.Driver.Base.PostgreSQL is
-------------
-- query --
-------------
function query (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => False);
end query;
---------------
-- prepare --
---------------
function prepare (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => True);
end prepare;
----------------------
-- prepare_select --
----------------------
function prepare_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => True,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end prepare_select;
--------------------
-- query_select --
--------------------
function query_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => False,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end query_select;
--------------------
-- sql_assemble --
--------------------
function sql_assemble (distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0) return String
is
rockyroad : CT.Text;
vanilla : String := assembly_common_select
(distinct, tables, columns, conditions, groupby, having, order);
begin
case null_sort is
when native => rockyroad := CT.SUS (vanilla);
when nulls_first => rockyroad := CT.SUS (vanilla & " NULLS FIRST");
when nulls_last => rockyroad := CT.SUS (vanilla & " NULLS LAST");
end case;
if limit > 0 then
if offset > 0 then
return CT.USS (rockyroad) & " LIMIT" & limit'Img &
" OFFSET" & offset'Img;
else
return CT.USS (rockyroad) & " LIMIT" & limit'Img;
end if;
end if;
return CT.USS (rockyroad);
end sql_assemble;
------------------
-- initialize --
------------------
overriding
procedure initialize (Object : in out PostgreSQL_Driver) is
begin
Object.connection := Object.local_connection'Unchecked_Access;
Object.dialect := driver_postgresql;
end initialize;
-----------------------
-- private_connect --
-----------------------
overriding
procedure private_connect (driver : out PostgreSQL_Driver;
database : String;
username : String;
password : String;
hostname : String := blankstring;
socket : String := blankstring;
port : Posix_Port := portless)
is
err1 : constant CT.Text :=
CT.SUS ("ACK! Reconnection attempted on active connection");
nom : constant CT.Text :=
CT.SUS ("Connection to " & database & " database succeeded.");
begin
if driver.connection_active then
driver.log_problem (category => execution,
message => err1);
return;
end if;
driver.connection.connect (database => database,
username => username,
password => password,
socket => socket,
hostname => hostname,
port => port);
driver.connection_active := driver.connection.connected;
driver.log_nominal (category => connecting, message => nom);
exception
when Error : others =>
driver.log_problem
(category => connecting,
break => True,
message => CT.SUS (CON.EX.Exception_Message (X => Error)));
end private_connect;
---------------
-- execute --
---------------
overriding
function execute (driver : PostgreSQL_Driver; sql : String)
return Affected_Rows
is
trsql : String := CT.trim_sql (sql);
nquery : Natural := CT.count_queries (trsql);
aborted : constant Affected_Rows := 0;
err1 : constant CT.Text :=
CT.SUS ("ACK! Execution attempted on inactive connection");
err2 : constant String :=
"Driver is configured to allow only one query at " &
"time, but this SQL contains multiple queries: ";
begin
if not driver.connection_active then
-- Fatal attempt to query an unccnnected database
driver.log_problem (category => execution,
message => err1,
break => True);
return aborted;
end if;
if nquery > 1 and then not driver.trait_multiquery_enabled then
-- Fatal attempt to execute multiple queries when it's not permitted
driver.log_problem (category => execution,
message => CT.SUS (err2 & trsql),
break => True);
return aborted;
end if;
declare
result : Affected_Rows;
begin
-- In order to support INSERT INTO .. RETURNING, we have to execute
-- multiqueries individually because we are scanning the first 7
-- characters to be "INSERT " after converting to upper case.
for query_index in Positive range 1 .. nquery loop
result := 0;
if nquery = 1 then
driver.connection.execute (trsql);
driver.log_nominal (execution, CT.SUS (trsql));
else
declare
SQ : constant String := CT.subquery (trsql, query_index);
begin
driver.connection.execute (SQ);
driver.log_nominal (execution, CT.SUS (SQ));
end;
end if;
end loop;
result := driver.connection.rows_affected_by_execution;
return result;
exception
when CON.QUERY_FAIL =>
driver.log_problem (category => execution,
message => CT.SUS (trsql),
pull_codes => True);
return aborted;
end;
end execute;
-------------------------
-- private_statement --
-------------------------
function private_statement (driver : PostgreSQL_Driver;
sql : String;
prepared : Boolean)
return SMT.PostgreSQL_statement
is
stype : AID.ASB.Stmt_Type := AID.ASB.direct_statement;
logcat : Log_Category := execution;
duplicate : aliased String := sql;
err1 : constant CT.Text :=
CT.SUS ("ACK! Query attempted on inactive connection");
begin
if prepared then
stype := AID.ASB.prepared_statement;
logcat := statement_preparation;
end if;
if driver.connection_active then
global_statement_counter := global_statement_counter + 1;
declare
buffered_mode : constant Boolean := not driver.async_cmd_mode;
statement : SMT.PostgreSQL_statement
(type_of_statement => stype,
log_handler => logger'Access,
pgsql_conn => CON.PostgreSQL_Connection_Access
(driver.connection),
identifier => global_statement_counter,
initial_sql => duplicate'Unchecked_Access,
con_error_mode => driver.trait_error_mode,
con_case_mode => driver.trait_column_case,
con_max_blob => driver.trait_max_blob_size,
con_buffered => buffered_mode);
begin
if not prepared then
if statement.successful then
driver.log_nominal
(category => logcat,
message => CT.SUS ("query succeeded," &
statement.rows_returned'Img & " rows returned"));
else
driver.log_nominal (category => execution,
message => CT.SUS ("Query failed!"));
end if;
end if;
return statement;
exception
when RES : others =>
-- Fatal attempt to prepare a statement
-- Logged already by stmt initialization
-- Should be internally marked as unsuccessful
return statement;
end;
else
-- Fatal attempt to query an unconnected database
driver.log_problem (category => logcat,
message => err1,
break => True);
end if;
-- We never get here, the driver.log_problem throws exception first
raise CON.STMT_NOT_VALID
with "failed to return statement";
end private_statement;
--------------------------------
-- trait_query_buffers_used --
--------------------------------
function trait_query_buffers_used (driver : PostgreSQL_Driver)
return Boolean is
begin
return not (driver.async_cmd_mode);
end trait_query_buffers_used;
------------------------------
-- set_query_buffers_used --
------------------------------
procedure set_trait_query_buffers_used (driver : PostgreSQL_Driver;
trait : Boolean)
is
-- Once the asynchronous command mode is supported (meaning that the
-- driver has to manually coordinate sending the queries and fetching
-- the rows one by one), then this procedure just changes
-- driver.async_cmd_mode => False.
begin
raise CON.UNSUPPORTED_BY_PGSQL
with "Single row mode is not currently supported";
end set_trait_query_buffers_used;
end AdaBase.Driver.Base.PostgreSQL;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
package body AdaBase.Driver.Base.PostgreSQL is
-------------
-- query --
-------------
function query (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => False);
end query;
---------------
-- prepare --
---------------
function prepare (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => True);
end prepare;
----------------------
-- prepare_select --
----------------------
function prepare_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => True,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end prepare_select;
--------------------
-- query_select --
--------------------
function query_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => False,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end query_select;
--------------------
-- sql_assemble --
--------------------
function sql_assemble (distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : Null_Priority := native;
limit : Trax_ID := 0;
offset : Trax_ID := 0) return String
is
rockyroad : CT.Text;
vanilla : String := assembly_common_select
(distinct, tables, columns, conditions, groupby, having, order);
begin
rockyroad := CT.SUS (vanilla);
if not CT.IsBlank (order) and then null_sort /= native then
case null_sort is
when native => null;
when nulls_first => CT.SU.Append (rockyroad, " NULLS FIRST");
when nulls_last => CT.SU.Append (rockyroad, " NULLS LAST");
end case;
end if;
if limit > 0 then
if offset > 0 then
return CT.USS (rockyroad) & " LIMIT" & limit'Img &
" OFFSET" & offset'Img;
else
return CT.USS (rockyroad) & " LIMIT" & limit'Img;
end if;
end if;
return CT.USS (rockyroad);
end sql_assemble;
------------------
-- initialize --
------------------
overriding
procedure initialize (Object : in out PostgreSQL_Driver) is
begin
Object.connection := Object.local_connection'Unchecked_Access;
Object.dialect := driver_postgresql;
end initialize;
-----------------------
-- private_connect --
-----------------------
overriding
procedure private_connect (driver : out PostgreSQL_Driver;
database : String;
username : String;
password : String;
hostname : String := blankstring;
socket : String := blankstring;
port : Posix_Port := portless)
is
err1 : constant CT.Text :=
CT.SUS ("ACK! Reconnection attempted on active connection");
nom : constant CT.Text :=
CT.SUS ("Connection to " & database & " database succeeded.");
begin
if driver.connection_active then
driver.log_problem (category => execution,
message => err1);
return;
end if;
driver.connection.connect (database => database,
username => username,
password => password,
socket => socket,
hostname => hostname,
port => port);
driver.connection_active := driver.connection.connected;
driver.log_nominal (category => connecting, message => nom);
exception
when Error : others =>
driver.log_problem
(category => connecting,
break => True,
message => CT.SUS (CON.EX.Exception_Message (X => Error)));
end private_connect;
---------------
-- execute --
---------------
overriding
function execute (driver : PostgreSQL_Driver; sql : String)
return Affected_Rows
is
trsql : String := CT.trim_sql (sql);
nquery : Natural := CT.count_queries (trsql);
aborted : constant Affected_Rows := 0;
err1 : constant CT.Text :=
CT.SUS ("ACK! Execution attempted on inactive connection");
err2 : constant String :=
"Driver is configured to allow only one query at " &
"time, but this SQL contains multiple queries: ";
begin
if not driver.connection_active then
-- Fatal attempt to query an unccnnected database
driver.log_problem (category => execution,
message => err1,
break => True);
return aborted;
end if;
if nquery > 1 and then not driver.trait_multiquery_enabled then
-- Fatal attempt to execute multiple queries when it's not permitted
driver.log_problem (category => execution,
message => CT.SUS (err2 & trsql),
break => True);
return aborted;
end if;
declare
result : Affected_Rows;
begin
-- In order to support INSERT INTO .. RETURNING, we have to execute
-- multiqueries individually because we are scanning the first 7
-- characters to be "INSERT " after converting to upper case.
for query_index in Positive range 1 .. nquery loop
result := 0;
if nquery = 1 then
driver.connection.execute (trsql);
driver.log_nominal (execution, CT.SUS (trsql));
else
declare
SQ : constant String := CT.subquery (trsql, query_index);
begin
driver.connection.execute (SQ);
driver.log_nominal (execution, CT.SUS (SQ));
end;
end if;
end loop;
result := driver.connection.rows_affected_by_execution;
return result;
exception
when CON.QUERY_FAIL =>
driver.log_problem (category => execution,
message => CT.SUS (trsql),
pull_codes => True);
return aborted;
end;
end execute;
-------------------------
-- private_statement --
-------------------------
function private_statement (driver : PostgreSQL_Driver;
sql : String;
prepared : Boolean)
return SMT.PostgreSQL_statement
is
stype : AID.ASB.Stmt_Type := AID.ASB.direct_statement;
logcat : Log_Category := execution;
duplicate : aliased String := sql;
err1 : constant CT.Text :=
CT.SUS ("ACK! Query attempted on inactive connection");
begin
if prepared then
stype := AID.ASB.prepared_statement;
logcat := statement_preparation;
end if;
if driver.connection_active then
global_statement_counter := global_statement_counter + 1;
declare
buffered_mode : constant Boolean := not driver.async_cmd_mode;
statement : SMT.PostgreSQL_statement
(type_of_statement => stype,
log_handler => logger'Access,
pgsql_conn => CON.PostgreSQL_Connection_Access
(driver.connection),
identifier => global_statement_counter,
initial_sql => duplicate'Unchecked_Access,
con_error_mode => driver.trait_error_mode,
con_case_mode => driver.trait_column_case,
con_max_blob => driver.trait_max_blob_size,
con_buffered => buffered_mode);
begin
if not prepared then
if statement.successful then
driver.log_nominal
(category => logcat,
message => CT.SUS ("query succeeded," &
statement.rows_returned'Img & " rows returned"));
else
driver.log_nominal (category => execution,
message => CT.SUS ("Query failed!"));
end if;
end if;
return statement;
exception
when RES : others =>
-- Fatal attempt to prepare a statement
-- Logged already by stmt initialization
-- Should be internally marked as unsuccessful
return statement;
end;
else
-- Fatal attempt to query an unconnected database
driver.log_problem (category => logcat,
message => err1,
break => True);
end if;
-- We never get here, the driver.log_problem throws exception first
raise CON.STMT_NOT_VALID
with "failed to return statement";
end private_statement;
--------------------------------
-- trait_query_buffers_used --
--------------------------------
function trait_query_buffers_used (driver : PostgreSQL_Driver)
return Boolean is
begin
return not (driver.async_cmd_mode);
end trait_query_buffers_used;
------------------------------
-- set_query_buffers_used --
------------------------------
procedure set_trait_query_buffers_used (driver : PostgreSQL_Driver;
trait : Boolean)
is
-- Once the asynchronous command mode is supported (meaning that the
-- driver has to manually coordinate sending the queries and fetching
-- the rows one by one), then this procedure just changes
-- driver.async_cmd_mode => False.
begin
raise CON.UNSUPPORTED_BY_PGSQL
with "Single row mode is not currently supported";
end set_trait_query_buffers_used;
end AdaBase.Driver.Base.PostgreSQL;
|
Fix NULLS FIRST/LAST logic
|
Fix NULLS FIRST/LAST logic
Don't add NULLS FIRST or NULLS LAST unless there's an order by clause.
|
Ada
|
isc
|
jrmarino/AdaBase
|
3ace48ad328d90986a573116864a06292f16985d
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
if Into.Current.Children = null then
Into.Current.Children := new Node_List;
-- Into.Current.Children.Current := Into.Current.Children.First'Access;
-- Into.Current.Children.Parent := Into.Current;
end if;
Append (Into.Current.Children.all, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
overriding
procedure Initialize (Doc : in out Document) is
begin
-- Doc.Nodes := Node_List_Refs.Create;
-- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access;
null;
end Initialize;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
end Wiki.Documents;
|
Drop the Initialize procedure
|
Drop the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
333f32dba521e3287f326f7017420354727bd58f
|
src/natools-web-cookie_setters.adb
|
src/natools-web-cookie_setters.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2019, 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.IO_Exceptions;
with Ada.Strings.Fixed;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Enumeration_IO;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Lockable;
with Natools.Web.Error_Pages;
package body Natools.Web.Cookie_Setters is
package Elements is
type Enum is
(Unknown,
Redirect_Target,
Force_Name,
Allowed_Names,
Path,
Comment,
Domain,
Max_Age,
Secure,
No_Secure,
HTTP_Only,
No_HTTP_Only,
Max_Length);
end Elements;
package Element_IO is new S_Expressions.Enumeration_IO.Typed_IO
(Elements.Enum);
procedure Execute
(Object : in out Setter;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Set_Cookie
(Object : in Setter;
Exchange : in out Sites.Exchange;
Key : in String;
Value : in String)
with Pre => Key'Length >= 1;
function To_Element (Name : in S_Expressions.Atom) return Elements.Enum;
procedure Update_Setter is new S_Expressions.Interpreter_Loop
(Setter, Meaningless_Type, Execute);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Execute
(Object : in out Setter;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use Elements;
use type S_Expressions.Events.Event;
begin
case To_Element (Name) is
when Unknown =>
Log (Severities.Error,
"Unknown cookie setter element """
& S_Expressions.To_String (Name) & '"');
when Redirect_Target =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Redirect_Target
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
end if;
when Force_Name =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Force_Name
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Force_Name.Reset;
end if;
when Allowed_Names =>
declare
Names : Containers.Unsafe_Atom_Lists.List;
begin
Containers.Append_Atoms (Names, Arguments);
Object.Allowed_Names := Containers.Create (Names);
end;
when Path =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Path
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Path.Reset;
end if;
when Comment =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Comment
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Comment.Reset;
end if;
when Domain =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Domain
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Domain.Reset;
end if;
when Max_Age =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
Object.Max_Age := Duration'Value
(S_Expressions.To_String (Arguments.Current_Atom));
exception
when Constraint_Error =>
Object.Max_Age := Default_Max_Age;
end;
end if;
when Secure =>
Object.Secure := True;
when No_Secure =>
Object.Secure := False;
when HTTP_Only =>
Object.HTTP_Only := True;
when No_HTTP_Only =>
Object.HTTP_Only := False;
when Max_Length =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
Object.Max_Length := Natural'Value
(S_Expressions.To_String (Arguments.Current_Atom));
exception
when Constraint_Error =>
Object.Max_Length := Default_Max_Length;
end;
end if;
end case;
end Execute;
procedure Set_Cookie
(Object : in Setter;
Exchange : in out Sites.Exchange;
Key : in String;
Value : in String)
is
use type Containers.Atom_Set;
begin
if Object.Force_Name.Is_Empty
and then Object.Allowed_Names /= Containers.Null_Atom_Set
and then not Containers.Contains
(Object.Allowed_Names, S_Expressions.To_Atom (Key))
then
return;
end if;
Exchange.Set_Cookie
(Key => Key,
Value => Value,
Comment => Comment (Object),
Domain => Domain (Object),
Max_Age => (if Value'Length > 0 then Object.Max_Age else 0.0),
Path => Path (Object),
Secure => Object.Secure,
HTTP_Only => Object.HTTP_Only);
end Set_Cookie;
function To_Element (Name : in S_Expressions.Atom) return Elements.Enum is
Result : Elements.Enum := Elements.Unknown;
begin
begin
Result := Element_IO.Value (Name);
exception
when Constraint_Error => null;
end;
return Result;
end To_Element;
----------------------
-- Public Interface --
----------------------
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class is
begin
return Loader'(File_Name
=> S_Expressions.Atom_Ref_Constructors.Create (File));
end Create;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom)
is
pragma Unmodified (Object);
Page : Setter;
begin
declare
File_Name : constant String
:= S_Expressions.To_String (Object.File_Name.Query);
begin
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader (File_Name);
begin
Update_Setter (Reader, Page, Meaningless_Value);
end;
if Page.Redirect_Target.Is_Empty then
Log (Severities.Error,
"Cookie setter file """ & File_Name
& """ defines no rediction target");
return;
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log (Severities.Warning,
"Unable to open cookie setter file """ & File_Name
& """, using it as a rediction target");
Page.Redirect_Target := Object.File_Name;
end;
Sites.Insert (Builder, Path, Page);
end Load;
overriding procedure Respond
(Object : in out Setter;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom)
is
pragma Unmodified (Object);
use type S_Expressions.Octet;
use type S_Expressions.Offset;
Arguments : constant String
:= (if Extra_Path'Length >= 1
and then Extra_Path (Extra_Path'First) = Character'Pos ('/')
then S_Expressions.To_String
(Extra_Path (Extra_Path'First + 1 .. Extra_Path'Last))
else S_Expressions.To_String (Extra_Path));
Separator : constant Natural := Ada.Strings.Fixed.Index (Arguments, "/");
begin
if Arguments'Length > Object.Max_Length then
return;
elsif not Object.Force_Name.Is_Empty then
Set_Cookie
(Object,
Exchange,
S_Expressions.To_String (Object.Force_Name.Query),
Arguments);
elsif Arguments'Length = 0 or Separator = Arguments'First then
return;
elsif Separator = 0 or Separator = Arguments'Last then
Set_Cookie
(Object,
Exchange,
Arguments,
"");
else
Set_Cookie
(Object,
Exchange,
Arguments (Arguments'First .. Separator - 1),
Arguments (Separator + 1 .. Arguments'Last));
end if;
Natools.Web.Error_Pages.See_Other
(Exchange,
Object.Redirect_Target.Query);
end Respond;
end Natools.Web.Cookie_Setters;
|
------------------------------------------------------------------------------
-- Copyright (c) 2019, 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.IO_Exceptions;
with Ada.Strings.Fixed;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Enumeration_IO;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Lockable;
with Natools.Web.Error_Pages;
package body Natools.Web.Cookie_Setters is
package Elements is
type Enum is
(Unknown,
Redirect_Target,
Force_Name,
Allowed_Names,
Path,
Comment,
Domain,
Max_Age,
Secure,
No_Secure,
HTTP_Only,
No_HTTP_Only,
Max_Length);
end Elements;
package Element_IO is new S_Expressions.Enumeration_IO.Typed_IO
(Elements.Enum);
procedure Execute
(Object : in out Setter;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Set_Cookie
(Object : in Setter;
Exchange : in out Sites.Exchange;
Key : in String;
Value : in String)
with Pre => Key'Length >= 1;
function To_Element (Name : in S_Expressions.Atom) return Elements.Enum;
procedure Update_Setter is new S_Expressions.Interpreter_Loop
(Setter, Meaningless_Type, Execute);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Execute
(Object : in out Setter;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use Elements;
use type S_Expressions.Events.Event;
begin
case To_Element (Name) is
when Unknown =>
Log (Severities.Error,
"Unknown cookie setter element """
& S_Expressions.To_String (Name) & '"');
when Redirect_Target =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Redirect_Target
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
end if;
when Force_Name =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Force_Name
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Force_Name.Reset;
end if;
when Allowed_Names =>
declare
Names : Containers.Unsafe_Atom_Lists.List;
begin
Containers.Append_Atoms (Names, Arguments);
Object.Allowed_Names := Containers.Create (Names);
end;
when Path =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Path
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Path.Reset;
end if;
when Comment =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Comment
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Comment.Reset;
end if;
when Domain =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Object.Domain
:= S_Expressions.Atom_Ref_Constructors.Create
(Arguments.Current_Atom);
else
Object.Domain.Reset;
end if;
when Max_Age =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
Object.Max_Age := Duration'Value
(S_Expressions.To_String (Arguments.Current_Atom));
exception
when Constraint_Error =>
Object.Max_Age := Default_Max_Age;
end;
end if;
when Secure =>
Object.Secure := True;
when No_Secure =>
Object.Secure := False;
when HTTP_Only =>
Object.HTTP_Only := True;
when No_HTTP_Only =>
Object.HTTP_Only := False;
when Max_Length =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
Object.Max_Length := Natural'Value
(S_Expressions.To_String (Arguments.Current_Atom));
exception
when Constraint_Error =>
Object.Max_Length := Default_Max_Length;
end;
end if;
end case;
end Execute;
procedure Set_Cookie
(Object : in Setter;
Exchange : in out Sites.Exchange;
Key : in String;
Value : in String)
is
use type Containers.Atom_Set;
begin
if Object.Force_Name.Is_Empty
and then Object.Allowed_Names /= Containers.Null_Atom_Set
and then not Containers.Contains
(Object.Allowed_Names, S_Expressions.To_Atom (Key))
then
return;
end if;
Exchange.Set_Cookie
(Key => Key,
Value => Value,
Comment => Comment (Object),
Domain => Domain (Object),
Max_Age => (if Value'Length > 0 then Object.Max_Age else 0.0),
Path => Path (Object),
Secure => Object.Secure,
HTTP_Only => Object.HTTP_Only);
end Set_Cookie;
function To_Element (Name : in S_Expressions.Atom) return Elements.Enum is
Result : Elements.Enum := Elements.Unknown;
begin
begin
Result := Element_IO.Value (Name);
exception
when Constraint_Error => null;
end;
return Result;
end To_Element;
----------------------
-- Public Interface --
----------------------
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class is
begin
return Loader'(File_Name
=> S_Expressions.Atom_Ref_Constructors.Create (File));
end Create;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom)
is
pragma Unmodified (Object);
Page : Setter;
begin
declare
File_Name : constant String
:= S_Expressions.To_String (Object.File_Name.Query);
begin
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader (File_Name);
begin
Update_Setter (Reader, Page, Meaningless_Value);
end;
if Page.Redirect_Target.Is_Empty then
Log (Severities.Error,
"Cookie setter file """ & File_Name
& """ defines no rediction target");
return;
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log (Severities.Warning,
"Unable to open cookie setter file """ & File_Name
& """, using it as a rediction target");
Page.Redirect_Target := Object.File_Name;
end;
Sites.Insert (Builder, Path, Page);
end Load;
overriding procedure Respond
(Object : in out Setter;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom)
is
pragma Unmodified (Object);
use type S_Expressions.Octet;
use type S_Expressions.Offset;
Arguments : constant String
:= (if Extra_Path'Length >= 1
and then Extra_Path (Extra_Path'First) = Character'Pos ('/')
then S_Expressions.To_String
(Extra_Path (Extra_Path'First + 1 .. Extra_Path'Last))
else S_Expressions.To_String (Extra_Path));
Separator : constant Natural := Ada.Strings.Fixed.Index (Arguments, "/");
begin
if Arguments'Length > Object.Max_Length then
return;
elsif not Object.Force_Name.Is_Empty then
Set_Cookie
(Object,
Exchange,
S_Expressions.To_String (Object.Force_Name.Query),
Arguments);
elsif Arguments'Length = 0 or Separator = Arguments'First then
return;
elsif Separator = 0 or Separator = Arguments'Last then
Set_Cookie
(Object,
Exchange,
Arguments
(Arguments'First
.. (if Separator = 0 then Arguments'Last else Separator - 1)),
"");
else
Set_Cookie
(Object,
Exchange,
Arguments (Arguments'First .. Separator - 1),
Arguments (Separator + 1 .. Arguments'Last));
end if;
Natools.Web.Error_Pages.See_Other
(Exchange,
Object.Redirect_Target.Query);
end Respond;
end Natools.Web.Cookie_Setters;
|
fix cookie name in removal
|
cookie_setters: fix cookie name in removal
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
36f4b964ef866deaa2cd513f7a79dba0657950e9
|
src/lzma/util-streams-buffered-lzma.ads
|
src/lzma/util-streams-buffered-lzma.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Lzma;
package Util.Streams.Buffered.Lzma is
-- -----------------------
-- Compress stream
-- -----------------------
-- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to
-- compress the data before writing it to the output.
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Compress_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Compress_Stream);
private
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Transform : Util.Encoders.Transformer_Access;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Compress_Stream);
end Util.Streams.Buffered.Lzma;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders;
package Util.Streams.Buffered.Lzma is
-- -----------------------
-- Compress stream
-- -----------------------
-- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to
-- compress the data before writing it to the output.
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Compress_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Compress_Stream);
private
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Transform : Util.Encoders.Transformer_Access;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Compress_Stream);
end Util.Streams.Buffered.Lzma;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1418b1121a18eb6d9b74cce05419b7ff076c5a7e
|
src/sys/encoders/util-encoders.ads
|
src/sys/encoders/util-encoders.ads
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009 - 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.Streams;
with Ada.Finalization;
with Interfaces;
-- = Encoders =
-- The `Util.Encoders` package defines the `Encoder` and `Decoder` types
-- which provide a mechanism to transform a stream from one format into
-- another format. The basic encoder and decoder support `base16`, `base64`,
-- `base64url` and `sha1`.
-- The following code extract will encode in `base64`:
--
-- C : constant Encoder := Util.Encoders.Create ("base64");
-- S : constant String := C.Encode ("Ada is great!");
--
-- and the next code extract will decode the `base64`:
--
-- D : constant Decoder := Util.Encoders.Create ("base64");
-- S : constant String := D.Decode ("QWRhIGlzIGdyZWF0IQ==");
--
-- To use the packages described here, use the following GNAT project:
--
-- with "utilada_sys";
--
-- @include util-encoders-ecc.ads
--
package Util.Encoders is
pragma Preelaborate;
use Ada.Streams;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Secret key
-- ------------------------------
-- A secret key of the given length, it cannot be copied and is safely erased.
subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last;
type Secret_Key (Length : Key_Length) is limited private;
-- Create the secret key from the password string.
function Create (Password : in String) return Secret_Key
with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length;
procedure Create (Password : in String;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
procedure Create (Password : in Stream_Element_Array;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
function Encode_Binary (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Encode_Unsigned_16 (E : in Encoder;
Value : in Interfaces.Unsigned_16) return String;
function Encode_Unsigned_32 (E : in Encoder;
Value : in Interfaces.Unsigned_32) return String;
function Encode_Unsigned_64 (E : in Encoder;
Value : in Interfaces.Unsigned_64) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
function Decode_Binary (E : in Decoder;
Data : in String) return Ada.Streams.Stream_Element_Array;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Array;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Finalization;
type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record
Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0);
end record;
overriding
procedure Finalize (Object : in out Secret_Key);
-- Transform the input data into the target string.
procedure Convert (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array;
Into : out String);
type Encoder is limited new Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is limited new Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009 - 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.Streams;
with Ada.Finalization;
with Interfaces;
-- = Encoders =
-- The `Util.Encoders` package defines the `Encoder` and `Decoder` types
-- which provide a mechanism to transform a stream from one format into
-- another format. The basic encoder and decoder support `base16`, `base64`,
-- `base64url` and `sha1`.
-- The following code extract will encode in `base64`:
--
-- C : constant Encoder := Util.Encoders.Create ("base64");
-- S : constant String := C.Encode ("Ada is great!");
--
-- and the next code extract will decode the `base64`:
--
-- D : constant Decoder := Util.Encoders.Create ("base64");
-- S : constant String := D.Decode ("QWRhIGlzIGdyZWF0IQ==");
--
-- To use the packages described here, use the following GNAT project:
--
-- with "utilada_sys";
--
-- @include util-encoders-uri.ads
-- @include util-encoders-ecc.ads
--
package Util.Encoders is
pragma Preelaborate;
use Ada.Streams;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Secret key
-- ------------------------------
-- A secret key of the given length, it cannot be copied and is safely erased.
subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last;
type Secret_Key (Length : Key_Length) is limited private;
-- Create the secret key from the password string.
function Create (Password : in String) return Secret_Key
with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length;
procedure Create (Password : in String;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
procedure Create (Password : in Stream_Element_Array;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
function Encode_Binary (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Encode_Unsigned_16 (E : in Encoder;
Value : in Interfaces.Unsigned_16) return String;
function Encode_Unsigned_32 (E : in Encoder;
Value : in Interfaces.Unsigned_32) return String;
function Encode_Unsigned_64 (E : in Encoder;
Value : in Interfaces.Unsigned_64) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
function Decode_Binary (E : in Decoder;
Data : in String) return Ada.Streams.Stream_Element_Array;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Array;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Finalization;
type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record
Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0);
end record;
overriding
procedure Finalize (Object : in out Secret_Key);
-- Transform the input data into the target string.
procedure Convert (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array;
Into : out String);
type Encoder is limited new Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is limited new Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
Update for the documentation
|
Update for the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1f307105437198ba9daa8f70147db8893175963c
|
src/el-beans.ads
|
src/el-beans.ads
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- 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 EL.Beans is
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is limited interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is limited interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is limited interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- 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 EL.Beans is
pragma Preelaborate;
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is limited interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is limited interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is limited interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
Add preelaborate pragma
|
Add preelaborate pragma
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
18aa127907a571b628e36ea9234acb3c579c411a
|
src/util-streams-buffered.adb
|
src/util-streams-buffered.adb
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered 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.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 Buffered_Stream;
Output : in Output_Stream_Access;
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.Output := Output;
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 2;
if Output = null then
Stream.Read_Pos := Stream.Write_Pos;
end if;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Buffered_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.Output := null;
Stream.Input := null;
Stream.Write_Pos := Stream.Last;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
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 Buffered_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Input => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Buffered_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 Buffered_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write a raw character on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Char : in Character) is
begin
if Stream.Write_Pos > Stream.Last then
Stream.Flush;
if Stream.Write_Pos > Stream.Last then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
end if;
Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char));
Stream.Write_Pos := Stream.Write_Pos + 1;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in String) is
Start : Positive := Item'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Natural;
Size : Natural;
Char : Character;
begin
while Start <= Item'Last loop
Size := Item'Last - Start + 1;
Avail := Natural (Stream.Last - Pos + 1);
if Avail = 0 then
Stream.Flush;
Pos := Stream.Write_Pos;
Avail := Natural (Stream.Last - Pos + 1);
if Avail = 0 then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
end if;
if Avail < Size then
Size := Avail;
end if;
while Size > 0 loop
Char := Item (Start);
Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char));
Pos := Pos + 1;
Start := Start + 1;
Size := Size - 1;
end loop;
Stream.Write_Pos := Pos;
end loop;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C)));
end loop;
end if;
end Write;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_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
Stream.Flush;
Pos := Stream.Write_Pos;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
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;
-- 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
Stream.Flush;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
Stream.Write_Pos := Pos;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
procedure Flush (Stream : in out Buffered_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 Buffered_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;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Buffered_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.
-- ------------------------------
procedure Read (Stream : in out Buffered_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;
-- 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
-- Stream.Flush;
-- Stream.Output.Write (Buffer (Start .. Buffer'Last));
-- return;
-- end if;
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 Buffered_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 + 1;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos + 1;
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.
-- ------------------------------
procedure Finalize (Object : in out Buffered_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 Buffered_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered streams Stream utilities
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
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 Buffered_Stream;
Output : in Output_Stream_Access;
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.Output := Output;
Stream.Input := Input;
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 Buffered_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.Output := null;
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
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 Buffered_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Input => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Buffered_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 Buffered_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write a raw character on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Char : in Character) is
begin
if Stream.Write_Pos > Stream.Last then
Stream.Flush;
if Stream.Write_Pos > Stream.Last then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
end if;
Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char));
Stream.Write_Pos := Stream.Write_Pos + 1;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in String) is
Start : Positive := Item'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Natural;
Size : Natural;
Char : Character;
begin
while Start <= Item'Last loop
Size := Item'Last - Start + 1;
Avail := Natural (Stream.Last - Pos + 1);
if Avail = 0 then
Stream.Flush;
Pos := Stream.Write_Pos;
Avail := Natural (Stream.Last - Pos + 1);
if Avail = 0 then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
end if;
if Avail < Size then
Size := Avail;
end if;
while Size > 0 loop
Char := Item (Start);
Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char));
Pos := Pos + 1;
Start := Start + 1;
Size := Size - 1;
end loop;
Stream.Write_Pos := Pos;
end loop;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C)));
end loop;
end if;
end Write;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Buffered_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
Stream.Flush;
Pos := Stream.Write_Pos;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
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
Stream.Flush;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
procedure Flush (Stream : in out Buffered_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 Buffered_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 Buffered_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.
-- ------------------------------
procedure Read (Stream : in out Buffered_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 Buffered_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.
-- ------------------------------
procedure Finalize (Object : in out Buffered_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 Buffered_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
end Util.Streams.Buffered;
|
Fix issues when reading from the buffer stream
|
Fix issues when reading from the buffer stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f7e69dd763082214976d7c9406fe14683987aa8d
|
src/util-texts-transforms.ads
|
src/util-texts-transforms.ads
|
-----------------------------------------------------------------------
-- Util-texts -- Various Text Transformation Utilities
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Stream (<>) is limited private;
type Char is (<>);
type Input is array (Positive range <>) of Char;
with procedure Put (Buffer : in out Stream; C : in Character);
with function To_Upper (C : Char) return Char;
with function To_Lower (C : Char) return Char;
package Util.Texts.Transforms is
pragma Preelaborate;
-- Capitalize the string into the result stream.
procedure Capitalize (Content : in Input;
Into : in out Stream);
-- Capitalize the string
function Capitalize (Content : Input) return Input;
-- Translate the input string into an upper case string in the result stream.
procedure To_Upper_Case (Content : in Input;
Into : in out Stream);
-- Translate the input string into an upper case string.
function To_Upper_Case (Content : Input) return Input;
-- Translate the input string into a lower case string in the result stream.
procedure To_Lower_Case (Content : in Input;
Into : in out Stream);
function To_Lower_Case (Content : Input) return Input;
-- Write in the output stream the value as a \uNNNN encoding form.
procedure To_Hex (Into : in out Stream;
Value : in Char);
pragma Inline_Always (To_Hex);
-- Escape the content into the result stream using the JavaScript
-- escape rules.
procedure Escape_Java_Script (Content : in Input;
Into : in out Stream);
-- Escape the content into the result stream using the Java
-- escape rules.
procedure Escape_Java (Content : in Input;
Into : in out Stream);
-- Escape the content into the result stream using the XML
-- escape rules:
-- '<' -> '<'
-- '>' -> '>'
-- ''' -> '''
-- '&' -> '&'
-- -> '&#nnn;' if Character'Pos >= 128
procedure Escape_Xml (Content : in Input;
Into : in out Stream);
-- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence
-- in the output stream.
procedure Translate_Xml_Entity (Entity : in Input;
Into : in out Stream);
-- Unescape the XML entities from the content into the result stream.
-- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible
-- for writing the result in the stream. The XML entity starts with '&' and ends with ';'.
-- The '&' and ';' are part of the entity when given to the translator. If the trailing
-- ';' is not part of the entity, it means the entity was truncated or the end of input
-- stream is reached.
procedure Unescape_Xml (Content : in Input;
Translator : not null access
procedure (Entity : in Input;
Into : in out Stream) := Translate_Xml_Entity'Access;
Into : in out Stream);
private
procedure Put (Into : in out Stream;
Value : in String);
procedure Escape_Java (Content : in Input;
Escape_Single_Quote : in Boolean;
Into : in out Stream);
end Util.Texts.Transforms;
|
-----------------------------------------------------------------------
-- util-texts-transforms -- Various Text Transformation Utilities
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Stream (<>) is limited private;
type Char is (<>);
type Input is array (Positive range <>) of Char;
with procedure Put (Buffer : in out Stream; C : in Character);
with function To_Upper (C : Char) return Char;
with function To_Lower (C : Char) return Char;
package Util.Texts.Transforms is
pragma Preelaborate;
-- Capitalize the string into the result stream.
procedure Capitalize (Content : in Input;
Into : in out Stream);
-- Capitalize the string
function Capitalize (Content : Input) return Input;
-- Translate the input string into an upper case string in the result stream.
procedure To_Upper_Case (Content : in Input;
Into : in out Stream);
-- Translate the input string into an upper case string.
function To_Upper_Case (Content : Input) return Input;
-- Translate the input string into a lower case string in the result stream.
procedure To_Lower_Case (Content : in Input;
Into : in out Stream);
function To_Lower_Case (Content : Input) return Input;
-- Write in the output stream the value as a \uNNNN encoding form.
procedure To_Hex (Into : in out Stream;
Value : in Char);
pragma Inline_Always (To_Hex);
-- Escape the content into the result stream using the JavaScript
-- escape rules.
procedure Escape_Java_Script (Content : in Input;
Into : in out Stream);
-- Escape the content into the result stream using the Java
-- escape rules.
procedure Escape_Java (Content : in Input;
Into : in out Stream);
-- Escape the content into the result stream using the XML
-- escape rules:
-- '<' -> '<'
-- '>' -> '>'
-- ''' -> '''
-- '&' -> '&'
-- -> '&#nnn;' if Character'Pos >= 128
procedure Escape_Xml (Content : in Input;
Into : in out Stream);
-- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence
-- in the output stream.
procedure Translate_Xml_Entity (Entity : in Input;
Into : in out Stream);
-- Unescape the XML entities from the content into the result stream.
-- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible
-- for writing the result in the stream. The XML entity starts with '&' and ends with ';'.
-- The '&' and ';' are part of the entity when given to the translator. If the trailing
-- ';' is not part of the entity, it means the entity was truncated or the end of input
-- stream is reached.
procedure Unescape_Xml (Content : in Input;
Translator : not null access
procedure (Entity : in Input;
Into : in out Stream) := Translate_Xml_Entity'Access;
Into : in out Stream);
private
procedure Put (Into : in out Stream;
Value : in String);
procedure Escape_Java (Content : in Input;
Escape_Single_Quote : in Boolean;
Into : in out Stream);
end Util.Texts.Transforms;
|
Fix the header
|
Fix the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
358d0079d9d84e5d0f0f2bd642e1d540ebddc12e
|
mat/src/mat-targets-readers.adb
|
mat/src/mat-targets-readers.adb
|
-----------------------------------------------------------------------
-- mat-targets-readers - 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.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers");
MSG_BEGIN : constant MAT.Events.Internal_Reference := 0;
MSG_END : constant MAT.Events.Internal_Reference := 1;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
PID_NAME : aliased constant String := "pid";
EXE_NAME : aliased constant String := "exe";
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));
-- ------------------------------
-- Create a new process after the begin event is received from the event stream.
-- ------------------------------
procedure Create_Process (For_Servant : in out Process_Servant;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
For_Servant.Target.Create_Process (Pid => Pid,
Path => Path,
Process => For_Servant.Process);
For_Servant.Process.Events := For_Servant.Events;
MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory,
Reader => For_Servant.Reader.all);
end Create_Process;
procedure Probe_Begin (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Defs : in MAT.Events.Attribute_Table;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
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.Buffer, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
For_Servant.Create_Process (Pid, Path);
For_Servant.Reader.Read_Message (Msg);
For_Servant.Reader.Read_Event_Definitions (Msg);
end Probe_Begin;
overriding
procedure Dispatch (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
begin
case Id is
when MSG_BEGIN =>
For_Servant.Probe_Begin (Id, Params.all, Frame, Msg);
when MSG_END =>
null;
when others =>
null;
end case;
end Dispatch;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Process_Reader_Access) is
begin
Reader.Reader := Into'Unchecked_Access;
Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Reader (Reader.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;
Reader : in out MAT.Readers.Manager_Base'Class) is
Process_Reader : constant Process_Reader_Access
:= new Process_Servant;
begin
Process_Reader.Target := Target'Unrestricted_Access;
Process_Reader.Events := Reader.Get_Target_Events;
Register (Reader, Process_Reader);
end Initialize;
end MAT.Targets.Readers;
|
-----------------------------------------------------------------------
-- mat-targets-readers - 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.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers");
MSG_BEGIN : constant MAT.Events.Internal_Reference := 0;
MSG_END : constant MAT.Events.Internal_Reference := 1;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
M_ETEXT : constant MAT.Events.Internal_Reference := 3;
M_EDATA : 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";
ETEXT_NAME : aliased constant String := "etext";
EDATA_NAME : aliased constant String := "edata";
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 => ETEXT_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_ETEXT),
4 => (Name => EDATA_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_EDATA),
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 (For_Servant : in out Process_Servant;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
For_Servant.Target.Create_Process (Pid => Pid,
Path => Path,
Process => For_Servant.Process);
For_Servant.Process.Events := For_Servant.Events;
MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory,
Reader => For_Servant.Reader.all);
end Create_Process;
procedure Probe_Begin (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Defs : in MAT.Events.Attribute_Table;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
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.Buffer, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
For_Servant.Create_Process (Pid, Path);
For_Servant.Reader.Read_Message (Msg);
For_Servant.Reader.Read_Event_Definitions (Msg);
end Probe_Begin;
overriding
procedure Dispatch (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
begin
case Id is
when MSG_BEGIN =>
For_Servant.Probe_Begin (Id, Params.all, Frame, Msg);
when MSG_END =>
null;
when others =>
null;
end case;
end Dispatch;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Process_Reader_Access) is
begin
Reader.Reader := Into'Unchecked_Access;
Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Reader (Reader.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;
Reader : in out MAT.Readers.Manager_Base'Class) is
Process_Reader : constant Process_Reader_Access
:= new Process_Servant;
begin
Process_Reader.Target := Target'Unrestricted_Access;
Process_Reader.Events := Reader.Get_Target_Events;
Register (Reader, Process_Reader);
end Initialize;
end MAT.Targets.Readers;
|
Define the etext, edata and end attributes which are passed in the begin event probe
|
Define the etext, edata and end attributes which are passed in the begin event probe
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
bac8c42d5f9c174a6dd0a0481198689c9f1c60cc
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.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);
-- 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;
-- 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;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.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;
-- 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;
end record;
end Wiki.Documents;
|
Declare the Is_Root_Node function
|
Declare the Is_Root_Node function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2b380ee2cc42bb689616a96f870843d4d8bd9f75
|
mat/src/mat-events.ads
|
mat/src/mat-events.ads
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- 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 Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is new Interfaces.Unsigned_32;
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Ptr is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Stack : MAT.Types.Target_Addr;
Rusage : Rusage_Info;
Cur_Depth : Natural;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- 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 Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is (EVENT_BEGIN, EVENT_END, EVENT_MALLOC, EVENT_FREE, EVENT_REALLOC);
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Ptr is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Stack : MAT.Types.Target_Addr;
Rusage : Rusage_Info;
Cur_Depth : Natural;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
Change the Event_Type to an enum
|
Change the Event_Type to an enum
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7834ca8821abee5dfc983340d10ed2bbc9f741ff
|
regtests/util-streams-tests.adb
|
regtests/util-streams-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Streams.Base64;
with Util.Streams.AES;
with Util.Measures;
with Ada.IO_Exceptions;
with Ada.Streams.Stream_IO;
package body Util.Streams.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package AES_Caller is new Util.Test_Caller (Test, "Streams.AES");
package Caller is new Util.Test_Caller (Test, "Streams.Main");
generic
Mode : in Util.Encoders.AES.AES_Mode;
Label : in String;
procedure Test_AES_Mode (T : in out Test);
procedure Test_AES (T : in out Test;
Item : in String;
Count : in Positive;
Mode : in Util.Encoders.AES.AES_Mode;
Label : in String) is
Reader : aliased Util.Streams.Texts.Reader_Stream;
Decipher : aliased Util.Streams.AES.Decoding_Stream;
Cipher : aliased Util.Streams.AES.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Key : Util.Encoders.Secret_Key
:= Util.Encoders.Create ("0123456789abcdef0123456789abcdef");
begin
-- Print -> Cipher -> Decipher
Decipher.Initialize (64 * 1024);
Decipher.Set_Key (Key, Mode);
Cipher.Initialize (Decipher'Access, 1024);
Cipher.Set_Key (Key, Mode);
Print.Initialize (Cipher'Access);
for I in 1 .. Count loop
Print.Write (Item);
end loop;
Print.Flush;
Util.Tests.Assert_Equals (T,
Item'Length * Count,
Decipher.Get_Size,
Label & ": decipher buffer has the wrong size mode");
-- Read content in Decipher
Reader.Initialize (Decipher);
for I in 1 .. Count loop
declare
L : String (Item'Range) := (others => ' ');
begin
for J in L'Range loop
Reader.Read (L (J));
end loop;
Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value");
exception
when Ada.IO_Exceptions.Data_Error =>
Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)");
end;
end loop;
end Test_AES;
procedure Test_AES_Mode (T : in out Test) is
begin
for I in 1 .. 128 loop
Test_AES (T, "a", I, Mode, Label);
end loop;
for I in 1 .. 128 loop
Test_AES (T, "ab", I, Mode, Label);
end loop;
for I in 1 .. 128 loop
Test_AES (T, "abc", I, Mode, Label);
end loop;
end Test_AES_Mode;
procedure Test_AES_ECB is
new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB");
procedure Test_AES_CBC is
new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC");
procedure Test_AES_PCBC is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC");
procedure Test_AES_CFB is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB");
procedure Test_AES_OFB is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB");
procedure Test_AES_CTR is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR");
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Base64.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Access, Size => 5);
Buffer.Initialize (Output => Stream'Access,
Size => 1024);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
procedure Test_Copy_Stream (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Pat : constant String := "123456789abcdef0123456789";
Buf : Ada.Streams.Stream_Element_Array (1 .. Pat'Length);
Res : String (10 .. 10 + Pat'Length - 1);
begin
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Util.Streams.Copy (Pat, Buf);
end loop;
Util.Measures.Report (S, "Util.Streams.Copy (String)", 1000);
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Util.Streams.Copy (Buf, Res);
end loop;
Util.Measures.Report (S, "Util.Streams.Copy (Stream_Element_Array)", 1000);
end;
Util.Tests.Assert_Equals (T, Pat, Res, "Invalid copy");
end Test_Copy_Stream;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Copy",
Test_Copy_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read",
Test_Base64_Stream'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)",
Test_AES_ECB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)",
Test_AES_CBC'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)",
Test_AES_PCBC'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)",
Test_AES_CFB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)",
Test_AES_OFB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)",
Test_AES_CTR'Access);
end Add_Tests;
end Util.Streams.Tests;
|
-----------------------------------------------------------------------
-- util-streams-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Streams.Base64;
with Util.Streams.AES;
with Util.Streams.Buffered.Lzma;
with Util.Measures;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
package body Util.Streams.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package AES_Caller is new Util.Test_Caller (Test, "Streams.AES");
package Caller is new Util.Test_Caller (Test, "Streams.Main");
generic
Mode : in Util.Encoders.AES.AES_Mode;
Label : in String;
procedure Test_AES_Mode (T : in out Test);
procedure Test_AES (T : in out Test;
Item : in String;
Count : in Positive;
Mode : in Util.Encoders.AES.AES_Mode;
Label : in String) is
Reader : aliased Util.Streams.Texts.Reader_Stream;
Decipher : aliased Util.Streams.AES.Decoding_Stream;
Cipher : aliased Util.Streams.AES.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Key : Util.Encoders.Secret_Key
:= Util.Encoders.Create ("0123456789abcdef0123456789abcdef");
begin
-- Print -> Cipher -> Decipher
Decipher.Initialize (64 * 1024);
Decipher.Set_Key (Key, Mode);
Cipher.Produces (Decipher'Access, 1024);
Cipher.Set_Key (Key, Mode);
Print.Initialize (Cipher'Access);
for I in 1 .. Count loop
Print.Write (Item);
end loop;
Print.Flush;
Util.Tests.Assert_Equals (T,
Item'Length * Count,
Decipher.Get_Size,
Label & ": decipher buffer has the wrong size mode");
-- Read content in Decipher
Reader.Initialize (Decipher);
for I in 1 .. Count loop
declare
L : String (Item'Range) := (others => ' ');
begin
for J in L'Range loop
Reader.Read (L (J));
end loop;
Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value");
exception
when Ada.IO_Exceptions.Data_Error =>
Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)");
end;
end loop;
end Test_AES;
procedure Test_AES_File (T : in out Test;
Item : in String;
Count : in Positive;
Mode : in Util.Encoders.AES.AES_Mode;
Label : in String) is
use Ada.Strings.Unbounded;
Path : constant String := Util.Tests.Get_Test_Path ("stream-aes-" & Label & ".aes");
File : aliased File_Stream;
Decipher : aliased Util.Streams.AES.Decoding_Stream;
Cipher : aliased Util.Streams.AES.Encoding_Stream;
Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Reader : Util.Streams.Texts.Reader_Stream;
Key : Util.Encoders.Secret_Key
:= Util.Encoders.Create ("0123456789abcdef0123456789abcdef");
begin
-- Print -> Cipher -> File
File.Create (Mode => Out_File, Name => Path);
Cipher.Produces (File'Access, 32);
Cipher.Set_Key (Key, Mode);
Print.Initialize (Cipher'Access);
--Compress.Initialize (Cipher'Access, 1024);
--Print.Initialize (Compress'Access);
for I in 1 .. Count loop
Print.Write (Item & ASCII.LF);
end loop;
Print.Close;
-- File -> Decipher -> Reader
File.Open (Mode => In_File, Name => Path);
Decipher.Consumes (File'Access, 10240);
Decipher.Set_Key (Key, Mode);
Decompress.Initialize (Decipher'Access, 10240);
Reader.Initialize (From => Decipher'Access);
--Reader.Initialize (From => Decompress'Access);
declare
Line_Count : Natural := 0;
begin
while not Reader.Is_Eof loop
declare
Line : Unbounded_String;
begin
Reader.Read_Line (Line);
exit when Length (Line) = 0;
if Item & ASCII.LF /= Line then
Util.Tests.Assert_Equals (T, Item & ASCII.LF, To_String (Line));
end if;
Line_Count := Line_Count + 1;
end;
end loop;
File.Close;
Util.Tests.Assert_Equals (T, Count, Line_Count);
end;
end Test_AES_File;
procedure Test_AES_Mode (T : in out Test) is
begin
for I in 1 .. 128 loop
Test_AES (T, "a", I, Mode, Label);
end loop;
for I in 1 .. 128 loop
Test_AES (T, "ab", I, Mode, Label);
end loop;
for I in 1 .. 128 loop
Test_AES (T, "abc", I, Mode, Label);
end loop;
Test_AES_File (T, "abcdefgh", 1000, Mode, Label);
end Test_AES_Mode;
procedure Test_AES_ECB is
new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB");
procedure Test_AES_CBC is
new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC");
procedure Test_AES_PCBC is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC");
procedure Test_AES_CFB is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB");
procedure Test_AES_OFB is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB");
procedure Test_AES_CTR is
new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR");
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Base64.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Access, Size => 5);
Buffer.Produces (Output => Stream'Access,
Size => 1024);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
procedure Test_Copy_Stream (T : in out Test) is
Pat : constant String := "123456789abcdef0123456789";
Buf : Ada.Streams.Stream_Element_Array (1 .. Pat'Length);
Res : String (10 .. 10 + Pat'Length - 1);
begin
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Util.Streams.Copy (Pat, Buf);
end loop;
Util.Measures.Report (S, "Util.Streams.Copy (String)", 1000);
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Util.Streams.Copy (Buf, Res);
end loop;
Util.Measures.Report (S, "Util.Streams.Copy (Stream_Element_Array)", 1000);
end;
Util.Tests.Assert_Equals (T, Pat, Res, "Invalid copy");
end Test_Copy_Stream;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Copy",
Test_Copy_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read",
Test_Base64_Stream'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)",
Test_AES_ECB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)",
Test_AES_CBC'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)",
Test_AES_PCBC'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)",
Test_AES_CFB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)",
Test_AES_OFB'Access);
AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)",
Test_AES_CTR'Access);
end Add_Tests;
end Util.Streams.Tests;
|
Add Test_AES_File to check the encryption+decryption streams and verifying the result
|
Add Test_AES_File to check the encryption+decryption streams and verifying the result
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9c38962e4ed759ae51fe54c367345bbc4e7e7d46
|
src/http/util-mail.ads
|
src/http/util-mail.ads
|
-----------------------------------------------------------------------
-- util-mail -- Mail Utility Library
-- 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 Ada.Strings.Unbounded;
-- == Introduction ==
-- The <tt>Util.Mail</tt> package provides various operations related to sending email.
package Util.Mail is
type Email_Address is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Address : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Parse the email address and separate the name from the address.
function Parse_Address (E_Mail : in String) return Email_Address;
-- Extract a first name from the email address.
function Get_First_Name (From : in Email_Address) return String;
end Util.Mail;
|
-----------------------------------------------------------------------
-- util-mail -- Mail Utility Library
-- 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 Ada.Strings.Unbounded;
-- == Introduction ==
-- The <tt>Util.Mail</tt> package provides various operations related to sending email.
package Util.Mail is
type Email_Address is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Address : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Parse the email address and separate the name from the address.
function Parse_Address (E_Mail : in String) return Email_Address;
-- Extract a first name from the email address.
function Get_First_Name (From : in Email_Address) return String;
-- Extract a last name from the email address.
function Get_Last_Name (From : in Email_Address) return String;
end Util.Mail;
|
Declare the Get_Last_Name function
|
Declare the Get_Last_Name function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
149d84744b184b190bf9159076e0b6f821fcf7bf
|
matp/src/events/mat-events-timelines.adb
|
matp/src/events/mat-events-timelines.adb
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Prev_Event : MAT.Events.Targets.Probe_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Targets.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.Start_Id := Event.Id;
Info.Start_Time := Event.Time;
end if;
Info.End_Id := Event.Id;
Info.End_Time := Event.Time;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.Start_Id := First_Event.Id;
Info.Start_Time := First_Event.Time;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
-- ------------------------------
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Id : MAT.Events.Targets.Event_Id_Type;
Last_Id : MAT.Events.Targets.Event_Id_Type;
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.Targets.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
-- ------------------------------
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.Targets.MSG_MALLOC
and Event.Index /= MAT.Events.Targets.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
-- ------------------------------
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
begin
for I in Backtrace'Range loop
exit when I > Depth;
declare
Pos : constant MAT.Events.Targets.Frame_Event_Info_Cursor
:= Frames.Find (Backtrace (I));
begin
if MAT.Events.Targets.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
Frames.Insert (Backtrace (I), Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
end MAT.Events.Timelines;
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Prev_Event : MAT.Events.Targets.Probe_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Targets.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.Start_Id := Event.Id;
Info.Start_Time := Event.Time;
end if;
Info.End_Id := Event.Id;
Info.End_Time := Event.Time;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.Start_Id := First_Event.Id;
Info.Start_Time := First_Event.Time;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
-- ------------------------------
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Id : MAT.Events.Targets.Event_Id_Type;
Last_Id : MAT.Events.Targets.Event_Id_Type;
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.Targets.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
-- ------------------------------
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.Targets.MSG_MALLOC
and Event.Index /= MAT.Events.Targets.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
-- ------------------------------
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
begin
for I in Backtrace'Range loop
exit when I > Depth;
declare
Pos : constant MAT.Events.Targets.Frame_Event_Info_Cursor
:= Frames.Find (Backtrace (I));
begin
if MAT.Events.Targets.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Frame_Addr := Backtrace (I);
Info.Count := 1;
Frames.Insert (Backtrace (I), Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
end MAT.Events.Timelines;
|
Store the frame address in the event info object
|
Store the frame address in the event info object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ccea1a78348ce1b6f5ac3903ddaf30ca5c72d67d
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- 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 Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Util.Refs;
with MAT.Types;
with MAT.Memory.Targets;
package MAT.Symbols.Targets is
-- The <tt>Library_Symbols</tt> holds the symbol table associated with
-- a shared library loaded by the program. The <tt>Text_Addr</tt> indicates
-- the text segment address of the loaded library.
type Library_Symbols is new Util.Refs.Ref_Entity with record
Text_Addr : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Library_Symbols_Access is access all Library_Symbols;
package Library_Symbols_Refs is
new Util.Refs.References (Library_Symbols, Library_Symbols_Access);
subtype Library_Symbols_Ref is Library_Symbols_Refs.Ref;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Library_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Library_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- 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 Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Util.Refs;
with MAT.Types;
with MAT.Memory.Targets;
package MAT.Symbols.Targets is
-- The <tt>Library_Symbols</tt> holds the symbol table associated with
-- a shared library loaded by the program. The <tt>Text_Addr</tt> indicates
-- the text segment address of the loaded library.
type Library_Symbols is new Util.Refs.Ref_Entity with record
Start_Addr : MAT.Types.Target_Addr;
End_Addr : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Library_Symbols_Access is access all Library_Symbols;
package Library_Symbols_Refs is
new Util.Refs.References (Library_Symbols, Library_Symbols_Access);
subtype Library_Symbols_Ref is Library_Symbols_Refs.Ref;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Library_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Library_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Add the end address to the library symbol object
|
Add the end address to the library symbol object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e670f9245e7ecfb1f4e0695a5acaf2e6faa93316
|
src/wiki-helpers-parser.adb
|
src/wiki-helpers-parser.adb
|
-----------------------------------------------------------------------
-- wiki-helpers-parser -- Generic procedure for the wiki parser
-- 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.Helpers;
with Wiki.Streams;
procedure Wiki.Helpers.Parser (Engine : in out Engine_Type;
Content : in Element_Type;
Doc : in out Wiki.Documents.Document) is
use type Wiki.Streams.Input_Stream_Access;
type Wide_Input is new Wiki.Streams.Input_Stream with record
Pos : Positive;
Len : Natural;
end record;
overriding
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean);
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean) is
begin
if Buf.Pos > Buf.Len then
Is_Eof := True;
Token := Wiki.Helpers.CR;
else
Token := Element (Content, Buf.Pos);
Buf.Pos := Buf.Pos + 1;
Is_Eof := False;
end if;
end Read;
Buffer : aliased Wide_Input;
begin
Buffer.Pos := 1;
Buffer.Len := Length (Content);
Parse (Engine, Buffer'Unchecked_Access, Doc);
end Wiki.Helpers.Parser;
|
-----------------------------------------------------------------------
-- wiki-helpers-parser -- Generic procedure for the wiki parser
-- 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.Helpers;
with Wiki.Streams;
procedure Wiki.Helpers.Parser (Engine : in out Engine_Type;
Content : in Element_Type;
Doc : in out Wiki.Documents.Document) is
use type Wiki.Streams.Input_Stream_Access;
type Wide_Input is new Wiki.Streams.Input_Stream with record
Pos : Positive;
Len : Natural;
end record;
overriding
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean);
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean) is
begin
if Buf.Pos <= Buf.Len then
Element (Content, Buf.Pos, Token);
Is_Eof := False;
else
Is_Eof := True;
Token := Wiki.Helpers.CR;
end if;
end Read;
Buffer : aliased Wide_Input;
begin
Buffer.Pos := 1;
Buffer.Len := Length (Content);
Parse (Engine, Buffer'Unchecked_Access, Doc);
end Wiki.Helpers.Parser;
|
Change the Element function into a procedure that also takes care of updating the position
|
Change the Element function into a procedure that also takes care of
updating the position
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
34df3280a23cab17f6bd018a6b3c737d3e9c4f2e
|
tools/druss-commands-bboxes.ads
|
tools/druss-commands-bboxes.ads
|
-----------------------------------------------------------------------
-- druss-commands-bboxes -- Commands to manage the bboxes
-- 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.
-----------------------------------------------------------------------
package Druss.Commands.Bboxes is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
procedure Discover (Command : in Command_Type;
Context : in out Context_Type);
-- Add the bbox with the given IP address.
procedure Add_Bbox (Command : in Command_Type;
IP : in String;
Context : in out Context_Type);
-- Enable or disable the bbox management by Druss.
procedure Do_Enable (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Set the password to be used by the Bbox API to connect to the box.
procedure Do_Password (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Druss.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Bboxes;
|
-----------------------------------------------------------------------
-- druss-commands-bboxes -- Commands to manage the bboxes
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Bboxes is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
procedure Discover (Command : in Command_Type;
Context : in out Context_Type);
-- Add the bbox with the given IP address.
procedure Add_Bbox (Command : in Command_Type;
IP : in String;
Context : in out Context_Type);
-- Enable or disable the bbox management by Druss.
procedure Do_Enable (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Set the password to be used by the Bbox API to connect to the box.
procedure Do_Password (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Druss.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Command_Type;
Context : in out Context_Type);
end Druss.Commands.Bboxes;
|
Change Help command to accept in out command
|
Change Help command to accept in out command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
b7f321661314d030e4775fe5b7c33c0cb2505b3d
|
awa/src/awa-services-filters.adb
|
awa/src/awa-services-filters.adb
|
-----------------------------------------------------------------------
-- awa-services-filters -- Setup service context in request processing flow
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Applications;
with AWA.Users.Principals;
with ASF.Principals;
package body AWA.Services.Filters is
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
-- ------------------------------
procedure Do_Filter (F : in Service_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
use type ASF.Principals.Principal_Access;
App : constant ASF.Servlets.Servlet_Registry_Access := ASF.Servlets.Get_Servlet_Context (Chain);
P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal;
Context : aliased AWA.Services.Contexts.Service_Context;
Principal : AWA.Users.Principals.Principal_Access;
Application : AWA.Applications.Application_Access;
begin
-- Get the user
if P /= null and then P.all in AWA.Users.Principals.Principal'Class then
Principal := AWA.Users.Principals.Principal'Class (P.all)'Access;
else
Principal := null;
end if;
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Setup the service context.
Context.Set_Context (Application, Principal);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end Do_Filter;
end AWA.Services.Filters;
|
-----------------------------------------------------------------------
-- awa-services-filters -- Setup service context in request processing flow
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Applications;
with AWA.Users.Principals;
with ASF.Principals;
package body AWA.Services.Filters is
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
-- ------------------------------
procedure Do_Filter (F : in Service_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
use type ASF.Principals.Principal_Access;
App : constant ASF.Servlets.Servlet_Registry_Access
:= ASF.Servlets.Get_Servlet_Context (Chain);
P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal;
Context : aliased AWA.Services.Contexts.Service_Context;
Principal : AWA.Users.Principals.Principal_Access;
Application : AWA.Applications.Application_Access;
begin
-- Get the user
if P /= null and then P.all in AWA.Users.Principals.Principal'Class then
Principal := AWA.Users.Principals.Principal'Class (P.all)'Access;
else
Principal := null;
end if;
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Setup the service context.
Context.Set_Context (Application, Principal);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end Do_Filter;
end AWA.Services.Filters;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3b4a783837295498b1880b2f773caf997b857964
|
UNIT_TESTS/init_002.adb
|
UNIT_TESTS/init_002.adb
|
with Test;
with OpenAL.Context;
with OpenAL.Context.Error;
procedure init_002 is
package ALC renames OpenAL.Context;
package ALC_Error renames OpenAL.Context.Error;
Device : ALC.Device_t;
Context : ALC.Context_t;
OK : Boolean;
use type ALC.Device_t;
use type ALC.Context_t;
use type ALC_Error.Error_t;
begin
Test.Initialize ("init_002");
Device := ALC.Open_Default_Device;
Test.Check_Test (12, "device opened", Device /= ALC.Invalid_Device);
Test.Check_Test (13, "no device error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
Context := ALC.Create_Context (Device);
Test.Check_Test (14, "context created", Context /= ALC.Invalid_Context);
Test.Check_Test (15, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
OK := ALC.Make_Context_Current (Context);
Test.Check_Test (16, "context made current", OK);
Test.Check_Test (17, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
OK := ALC.Make_Context_Current (ALC.Null_Context);
Test.Check_Test (18, "no context made current", OK);
Test.Check_Test (19, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
OK := ALC.Close_Device (Device);
Test.Check_Test (20, "device failed to close", OK = False);
Test.Check_Test (21, "device error", ALC_Error.Get_Error (Device) /= ALC_Error.No_Error);
Test.Finish;
end init_002;
|
with Test;
with OpenAL.Context;
with OpenAL.Context.Error;
procedure init_002 is
package ALC renames OpenAL.Context;
package ALC_Error renames OpenAL.Context.Error;
Device : ALC.Device_t;
Context : ALC.Context_t;
OK : Boolean;
use type ALC.Device_t;
use type ALC.Context_t;
use type ALC_Error.Error_t;
begin
Test.Initialize ("init_002");
Device := ALC.Open_Default_Device;
Test.Check_Test (12, "device opened", Device /= ALC.Invalid_Device);
Test.Check_Test (13, "no device error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
Context := ALC.Create_Context (Device);
Test.Check_Test (14, "context created", Context /= ALC.Invalid_Context);
Test.Check_Test (15, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
OK := ALC.Make_Context_Current (Context);
Test.Check_Test (16, "context made current", OK);
Test.Check_Test (17, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
OK := ALC.Make_Context_Current (ALC.Null_Context);
Test.Check_Test (18, "no context made current", OK);
Test.Check_Test (19, "no context error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
--
-- According to the 1.1 spec, this should return False.
-- Unfortunately, no implementation actually does that...
--
OK := ALC.Close_Device (Device);
Test.Check_Test (20, "device closed", OK);
Test.Check_Test (21, "device error", ALC_Error.Get_Error (Device) = ALC_Error.No_Error);
Test.Finish;
end init_002;
|
Adjust init_002
|
Adjust init_002
|
Ada
|
isc
|
io7m/coreland-openal-ada,io7m/coreland-openal-ada
|
e320287993069dc42dc359cb9fb914babcce2bff
|
src/babel-base-text.adb
|
src/babel-base-text.adb
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.ISO8601;
with Babel.Files.Sets;
with Babel.Files.Lifecycles;
with Ada.Text_IO;
package body Babel.Base.Text is
-- ------------------------------
-- Insert the file in the database.
-- ------------------------------
overriding
procedure Insert (Into : in out Text_Database;
File : in Babel.Files.File_Type) is
begin
Into.Files.Insert (File);
end Insert;
-- ------------------------------
-- Write the SHA1 checksum for the files stored in the map.
-- ------------------------------
procedure Save (Database : in Text_Database;
Path : in String) is
Checksum : Ada.Text_IO.File_Type;
procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is
File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position);
SHA1 : constant String := Babel.Files.Get_SHA1 (File);
Path : constant String := Babel.Files.Get_Path (File);
begin
Ada.Text_IO.Put (Checksum, SHA1);
Ada.Text_IO.Put (Checksum, Babel.Files.Uid_Type'Image (Babel.Files.Get_User (File)));
Ada.Text_IO.Put (Checksum, Babel.Files.Gid_Type'Image (Babel.Files.Get_Group (File)));
Ada.Text_IO.Put (Checksum, " ");
Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File)));
Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File)));
Ada.Text_IO.Put (Checksum, " ");
Ada.Text_IO.Put (Checksum, Path);
Ada.Text_IO.New_Line (Checksum);
end Write_Checksum;
begin
Ada.Text_IO.Create (File => Checksum, Name => Path);
Database.Files.Iterate (Write_Checksum'Access);
Ada.Text_IO.Close (File => Checksum);
end Save;
end Babel.Base.Text;
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.ISO8601;
with Babel.Files.Sets;
with Babel.Files.Lifecycles;
with Ada.Text_IO;
package body Babel.Base.Text is
-- ------------------------------
-- Insert the file in the database.
-- ------------------------------
overriding
procedure Insert (Into : in out Text_Database;
File : in Babel.Files.File_Type) is
begin
Into.Files.Insert (File);
end Insert;
-- ------------------------------
-- Write the SHA1 checksum for the files stored in the map.
-- ------------------------------
procedure Save (Database : in Text_Database;
Path : in String) is
Checksum : Ada.Text_IO.File_Type;
procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is
File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position);
SHA1 : constant String := Babel.Files.Get_SHA1 (File);
Path : constant String := Babel.Files.Get_Path (File);
begin
Ada.Text_IO.Put (Checksum, SHA1);
Ada.Text_IO.Put (Checksum, Babel.Uid_Type'Image (Babel.Files.Get_User (File)));
Ada.Text_IO.Put (Checksum, Babel.Gid_Type'Image (Babel.Files.Get_Group (File)));
Ada.Text_IO.Put (Checksum, " ");
Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File)));
Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File)));
Ada.Text_IO.Put (Checksum, " ");
Ada.Text_IO.Put (Checksum, Path);
Ada.Text_IO.New_Line (Checksum);
end Write_Checksum;
begin
Ada.Text_IO.Create (File => Checksum, Name => Path);
Database.Files.Iterate (Write_Checksum'Access);
Ada.Text_IO.Close (File => Checksum);
end Save;
end Babel.Base.Text;
|
Use Babel.Uid_Type and Babel.Gid_Type types
|
Use Babel.Uid_Type and Babel.Gid_Type types
|
Ada
|
apache-2.0
|
stcarrez/babel
|
b1cf6e7b8849fc8156b3631da4b3ec4c6b7290b1
|
samples/beans/users.adb
|
samples/beans/users.adb
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- 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 ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.Openid;
with ASF.Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.Openid;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.OpenID;
with ASF.Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.OpenID;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
procedure Remove_Cookie (Name : in String);
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.OpenID.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.OpenID.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.OpenID.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.OpenID.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
Fix some compilation warnings
|
Fix some compilation warnings
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
d8d9246dfddcccb37f16d934ce6f471630aa5ee0
|
src/gen-model-beans.ads
|
src/gen-model-beans.ads
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.Mappings;
with Gen.Model.Packages;
with Gen.Model.Tables;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_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 : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.Tables;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_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 : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
c8fae38751bf4e4ce3c4b1ba82bdd4a8b53a85f0
|
testutil/ahven/ahven-listeners-basic.adb
|
testutil/ahven/ahven-listeners-basic.adb
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ahven.AStrings;
package body Ahven.Listeners.Basic is
use Ahven.AStrings;
-- Because of Ada.Text_IO output capturing, the result
-- recording is happening in the End_Test procedure.
--
-- Add_{Pass,Failure,Error} procedures delegate result
-- saving to the Set_Last_Test_Info procedure, which
-- records the latest result to the listener.
procedure Set_Last_Test_Info (Listener : in out Basic_Listener;
Info : Context;
Result : Result_Type) is
begin
Listener.Last_Test_Result := Result;
if Info.Phase = TEST_RUN then
Results.Set_Routine_Name (Listener.Last_Info, Info.Routine_Name);
Results.Set_Test_Name (Listener.Last_Info, Info.Test_Name);
Results.Set_Message (Listener.Last_Info, Info.Message);
Results.Set_Long_Message (Listener.Last_Info, Info.Long_Message);
end if;
end Set_Last_Test_Info;
procedure Add_Pass (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, PASS_RESULT);
end Add_Pass;
procedure Add_Failure (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, FAILURE_RESULT);
end Add_Failure;
procedure Add_Skipped (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, SKIPPED_RESULT);
end Add_Skipped;
procedure Add_Error (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, ERROR_RESULT);
end Add_Error;
procedure Start_Test (Listener : in out Basic_Listener;
Info : Context) is
R : Result_Collection_Access := null;
begin
Listener.Start_Time := Ada.Calendar.Clock;
if Info.Test_Kind = CONTAINER then
R := new Result_Collection;
Set_Name (R.all, Info.Test_Name);
Set_Parent (R.all, Listener.Current_Result);
if Listener.Current_Result = null then
Add_Child (Listener.Main_Result, R);
else
Add_Child (Listener.Current_Result.all, R);
end if;
Listener.Current_Result := R;
elsif Listener.Capture_Output then
-- A test routine? Let's create a temporary file
-- and direct Ada.Text_IO output there (if requested).
Temporary_Output.Create_Temp (Listener.Output_File);
Temporary_Output.Redirect_Output (Listener.Output_File);
end if;
end Start_Test;
procedure End_Test (Listener : in out Basic_Listener;
Info : Context) is
use type Ada.Calendar.Time;
Execution_Time : constant Duration :=
Ada.Calendar.Clock - Listener.Start_Time;
procedure Add_Result (Collection : in out Result_Collection) is
My_Info : Result_Info := Listener.Last_Info;
begin
if Info.Phase = TEST_RUN then
Set_Routine_Name (My_Info, To_String (Info.Routine_Name));
end if;
-- It is possible that only Start_Test and End_Test
-- are called (e.g. for Test_Suite), so the latest
-- test result can be unset (set to NO_RESULT)
--
-- In that case, we simply jump to parent collection.
-- Otherwise, we record the result.
if Listener.Last_Test_Result /= NO_RESULT then
if Listener.Capture_Output then
-- End of the test routine, so we can restore
-- the normal output now and close the temporary file.
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
-- Saving the name of the temporary file to the test result,
-- so the file can be deleted later
Set_Output_File
(My_Info, Temporary_Output.Get_Name (Listener.Output_File));
end if;
Set_Message (My_Info, Get_Message (Listener.Last_Info));
Set_Long_Message (My_Info, Get_Long_Message (Listener.Last_Info));
Results.Set_Execution_Time (My_Info, Execution_Time);
case Listener.Last_Test_Result is
when PASS_RESULT =>
Add_Pass (Collection, My_Info);
when FAILURE_RESULT =>
Add_Failure (Collection, My_Info);
when ERROR_RESULT | NO_RESULT =>
Add_Error (Collection, My_Info);
when SKIPPED_RESULT =>
Add_Skipped (Collection, My_Info);
end case;
Listener.Last_Test_Result := NO_RESULT;
else
Listener.Current_Result :=
Get_Parent (Listener.Current_Result.all);
end if;
end Add_Result;
begin
if Listener.Current_Result /= null then
Add_Result (Listener.Current_Result.all);
else
Add_Result (Listener.Main_Result);
end if;
end End_Test;
procedure Set_Output_Capture (Listener : in out Basic_Listener;
Capture : Boolean) is
begin
Listener.Capture_Output := Capture;
end Set_Output_Capture;
function Get_Output_Capture (Listener : Basic_Listener)
return Boolean is
begin
return Listener.Capture_Output;
end Get_Output_Capture;
procedure Remove_File (Name : String) is
Handle : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (Handle, Ada.Text_IO.Out_File, Name);
Ada.Text_IO.Delete (Handle);
exception
when others =>
null; -- For now we can safely ignore errors (like missing file)
end Remove_File;
procedure Remove_Files (Collection : in out Result_Collection) is
procedure Remove (Name : Bounded_String) is
begin
if Length (Name) > 0 then
Remove_File (To_String (Name));
end if;
end Remove;
procedure Remove_Loop (First_Item : Result_Info_Cursor) is
Loop_Iter : Result_Info_Cursor := First_Item;
begin
loop
exit when not Is_Valid (Loop_Iter);
Remove (Get_Output_File (Data (Loop_Iter)));
Loop_Iter := Next (Loop_Iter);
end loop;
end Remove_Loop;
Child_Iter : Result_Collection_Cursor;
begin
Remove_Loop (First_Pass (Collection));
Remove_Loop (First_Failure (Collection));
Remove_Loop (First_Error (Collection));
Remove_Loop (First_Skipped (Collection));
Child_Iter := First_Child (Collection);
Child_Loop:
loop
exit Child_Loop when not Is_Valid (Child_Iter);
Remove_Files (Data (Child_Iter).all);
Child_Iter := Next (Child_Iter);
end loop Child_Loop;
end Remove_Files;
procedure Finalize (Listener : in out Basic_Listener) is
begin
Remove_Files (Listener.Main_Result);
Results.Release (Listener.Main_Result);
end Finalize;
end Ahven.Listeners.Basic;
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ahven.AStrings;
package body Ahven.Listeners.Basic is
use Ahven.AStrings;
-- Because of Ada.Text_IO output capturing, the result
-- recording is happening in the End_Test procedure.
--
-- Add_{Pass,Failure,Error} procedures delegate result
-- saving to the Set_Last_Test_Info procedure, which
-- records the latest result to the listener.
procedure Set_Last_Test_Info (Listener : in out Basic_Listener;
Info : Context;
Result : Result_Type) is
begin
Listener.Last_Test_Result := Result;
if Info.Phase = TEST_RUN then
Results.Set_Routine_Name (Listener.Last_Info, Info.Routine_Name);
Results.Set_Test_Name (Listener.Last_Info, Info.Test_Name);
Results.Set_Message (Listener.Last_Info, Info.Message);
Results.Set_Long_Message (Listener.Last_Info, Info.Long_Message);
end if;
end Set_Last_Test_Info;
procedure Add_Pass (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, PASS_RESULT);
end Add_Pass;
procedure Add_Failure (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, FAILURE_RESULT);
end Add_Failure;
procedure Add_Skipped (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, SKIPPED_RESULT);
end Add_Skipped;
procedure Add_Error (Listener : in out Basic_Listener;
Info : Context) is
begin
Set_Last_Test_Info (Listener, Info, ERROR_RESULT);
end Add_Error;
procedure Start_Test (Listener : in out Basic_Listener;
Info : Context) is
R : Result_Collection_Access := null;
begin
Listener.Start_Time := Ada.Calendar.Clock;
if Info.Test_Kind = CONTAINER then
R := new Result_Collection;
Set_Name (R.all, Info.Test_Name);
Set_Parent (R.all, Listener.Current_Result);
if Listener.Current_Result = null then
Add_Child (Listener.Main_Result, R);
else
Add_Child (Listener.Current_Result.all, R);
end if;
Listener.Current_Result := R;
elsif Listener.Capture_Output then
-- A test routine? Let's create a temporary file
-- and direct Ada.Text_IO output there (if requested).
Temporary_Output.Create_Temp (Listener.Output_File);
Temporary_Output.Redirect_Output (Listener.Output_File);
end if;
end Start_Test;
procedure End_Test (Listener : in out Basic_Listener;
Info : Context) is
use type Ada.Calendar.Time;
Execution_Time : constant Duration :=
Ada.Calendar.Clock - Listener.Start_Time;
procedure Add_Result (Collection : in out Result_Collection) is
My_Info : Result_Info := Listener.Last_Info;
begin
if Info.Phase = TEST_RUN then
Set_Routine_Name (My_Info, To_String (Info.Routine_Name));
end if;
-- It is possible that only Start_Test and End_Test
-- are called (e.g. for Test_Suite), so the latest
-- test result can be unset (set to NO_RESULT)
--
-- In that case, we simply jump to parent collection.
-- Otherwise, we record the result.
if Listener.Last_Test_Result /= NO_RESULT then
if Listener.Capture_Output then
-- End of the test routine, so we can restore
-- the normal output now and close the temporary file.
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
-- Saving the name of the temporary file to the test result,
-- so the file can be deleted later
Set_Output_File
(My_Info, Temporary_Output.Get_Name (Listener.Output_File));
end if;
Set_Message (My_Info, Get_Message (Listener.Last_Info));
Set_Long_Message (My_Info, Get_Long_Message (Listener.Last_Info));
Results.Set_Execution_Time (My_Info, Execution_Time);
case Listener.Last_Test_Result is
when PASS_RESULT =>
Add_Pass (Collection, My_Info);
when FAILURE_RESULT =>
Add_Failure (Collection, My_Info);
when ERROR_RESULT | NO_RESULT =>
Add_Error (Collection, My_Info);
when SKIPPED_RESULT =>
Add_Skipped (Collection, My_Info);
end case;
Listener.Last_Test_Result := NO_RESULT;
else
Listener.Current_Result :=
Get_Parent (Listener.Current_Result.all);
end if;
end Add_Result;
begin
if Listener.Current_Result /= null then
Add_Result (Listener.Current_Result.all);
else
Add_Result (Listener.Main_Result);
end if;
end End_Test;
procedure Set_Output_Capture (Listener : in out Basic_Listener;
Capture : Boolean) is
begin
Listener.Capture_Output := Capture;
end Set_Output_Capture;
function Get_Output_Capture (Listener : Basic_Listener)
return Boolean is
begin
return Listener.Capture_Output;
end Get_Output_Capture;
procedure Remove_File (Name : String) is
Handle : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (Handle, Ada.Text_IO.Out_File, Name);
Ada.Text_IO.Delete (Handle);
exception
when others =>
null; -- For now we can safely ignore errors (like missing file)
end Remove_File;
procedure Remove_Files (Collection : in out Result_Collection) is
procedure Remove (Name : Bounded_String) is
begin
if Length (Name) > 0 then
Remove_File (To_String (Name));
end if;
end Remove;
procedure Remove_Loop (First_Item : Result_Info_Cursor) is
Loop_Iter : Result_Info_Cursor := First_Item;
begin
loop
exit when not Is_Valid (Loop_Iter);
Remove (Get_Output_File (Data (Loop_Iter)));
Loop_Iter := Next (Loop_Iter);
end loop;
end Remove_Loop;
Child_Iter : Result_Collection_Cursor;
begin
Remove_Loop (First_Pass (Collection));
Remove_Loop (First_Failure (Collection));
Remove_Loop (First_Error (Collection));
Remove_Loop (First_Skipped (Collection));
Child_Iter := First_Child (Collection);
Child_Loop :
loop
exit Child_Loop when not Is_Valid (Child_Iter);
Remove_Files (Data (Child_Iter).all);
Child_Iter := Next (Child_Iter);
end loop Child_Loop;
end Remove_Files;
procedure Finalize (Listener : in out Basic_Listener) is
begin
Remove_Files (Listener.Main_Result);
Results.Release (Listener.Main_Result);
end Finalize;
end Ahven.Listeners.Basic;
|
Fix style warning
|
Fix style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
76d7d3c318509e08dbb82e2b3d968913ab18b3d8
|
awa/src/awa-modules-reader.adb
|
awa/src/awa-modules-reader.adb
|
-----------------------------------------------------------------------
-- awa-modules-reader -- Read module configuration files
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.XML;
with AWA.Applications.Configs;
with Security.Policies;
-- The <b>AWA.Modules.Reader</b> package reads the module configuration files
-- and initializes the module.
package body AWA.Modules.Reader is
-- ------------------------------
-- Read the module configuration file and configure the components
-- ------------------------------
procedure Read_Configuration (Plugin : in out Module'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access) is
Reader : Util.Serialize.IO.XML.Parser;
package Config is
new AWA.Applications.Configs.Reader_Config (Reader,
Plugin.App.all'Unchecked_Access,
Context,
False);
pragma Warnings (Off, Config);
Sec : constant Security.Policies.Policy_Manager_Access := Plugin.App.Get_Security_Manager;
begin
Log.Info ("Reading module configuration file {0}", File);
Sec.Prepare_Config (Reader);
if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
Sec.Finish_Config (Reader);
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
end AWA.Modules.Reader;
|
-----------------------------------------------------------------------
-- awa-modules-reader -- Read module configuration files
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers;
with AWA.Applications.Configs;
with Security.Policies;
-- The <b>AWA.Modules.Reader</b> package reads the module configuration files
-- and initializes the module.
package body AWA.Modules.Reader is
-- ------------------------------
-- Read the module configuration file and configure the components
-- ------------------------------
procedure Read_Configuration (Plugin : in out Module'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access) is
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
package Config is
new AWA.Applications.Configs.Reader_Config (Mapper,
Plugin.App.all'Unchecked_Access,
Context,
False);
pragma Warnings (Off, Config);
Sec : constant Security.Policies.Policy_Manager_Access := Plugin.App.Get_Security_Manager;
begin
Log.Info ("Reading module configuration file {0}", File);
Sec.Prepare_Config (Mapper);
if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.Mappers.Dump (Mapper, AWA.Modules.Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File, Mapper);
Sec.Finish_Config (Reader);
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
end AWA.Modules.Reader;
|
Update to use the new parser/mapper interface
|
Update to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cea4da18bc82ea0c61de80bf2bd01b7fa29e5ac8
|
awa/src/awa-components-wikis.ads
|
awa/src/awa-components-wikis.ads
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- 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 Util.Beans.Basic;
with Util.Beans.Objects;
with ASF.Contexts.Faces;
with ASF.Components;
with ASF.Components.Html;
with Wiki.Strings;
with Wiki.Render;
with Wiki.Render.Links;
package AWA.Components.Wikis is
use ASF.Contexts.Faces;
-- The wiki format of the wiki text. The valid values are:
-- dotclear, google, creole, phpbb, mediawiki
FORMAT_NAME : constant String := "format";
VALUE_NAME : constant String := ASF.Components.VALUE_NAME;
-- The link renderer bean that controls the generation of page and image links.
LINKS_NAME : constant String := "links";
-- ------------------------------
-- Wiki component
-- ------------------------------
--
-- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/>
--
type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record;
type UIWiki_Access is access all UIWiki'Class;
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax;
-- Get the links renderer that must be used to render image and page links.
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access;
-- Render the wiki text
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class);
use Ada.Strings.Wide_Wide_Unbounded;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Links.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- Make a link adding a prefix unless the link is already absolute.
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
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 Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
private
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean;
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- 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 Util.Beans.Basic;
with Util.Beans.Objects;
with ASF.Contexts.Faces;
with ASF.Components;
with ASF.Components.Html;
with Wiki.Strings;
with Wiki.Render;
with Wiki.Plugins;
with Wiki.Render.Links;
package AWA.Components.Wikis is
use ASF.Contexts.Faces;
-- The wiki format of the wiki text. The valid values are:
-- dotclear, google, creole, phpbb, mediawiki
FORMAT_NAME : constant String := "format";
VALUE_NAME : constant String := ASF.Components.VALUE_NAME;
-- The link renderer bean that controls the generation of page and image links.
LINKS_NAME : constant String := "links";
-- The plugin factory bean that must be used for Wiki plugins.
PLUGINS_NAME : constant String := "plugins";
-- ------------------------------
-- Wiki component
-- ------------------------------
--
-- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/>
--
type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record;
type UIWiki_Access is access all UIWiki'Class;
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax;
-- Get the links renderer that must be used to render image and page links.
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access;
-- Get the plugin factory that must be used by the Wiki parser.
function Get_Plugin_Factory (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Plugins.Plugin_Factory_Access;
-- Render the wiki text
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class);
use Ada.Strings.Wide_Wide_Unbounded;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Links.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- Make a link adding a prefix unless the link is already absolute.
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
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 Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
private
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean;
end AWA.Components.Wikis;
|
Declare Get_Plugin_Factory function
|
Declare Get_Plugin_Factory function
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4e45d42a855a243605011f19a936257ed2b3a113
|
awa/src/awa-users-principals.adb
|
awa/src/awa-users-principals.adb
|
-----------------------------------------------------------------------
-- awa-users-principals -- User principals
-- 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 AWA.Users.Principals is
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return From.User.Get_Name;
end Get_Name;
-- ------------------------------
-- Returns true if the given role is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Principal;
Role : in Security.Permissions.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal identifier (name)
-- ------------------------------
function Get_Id (From : in Principal) return String is
begin
return From.User.Get_Name;
end Get_Id;
-- ------------------------------
-- Get the user associated with the principal.
-- ------------------------------
function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is
begin
return From.User;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (From : in Principal) return ADO.Identifier is
begin
return From.User.Get_Id;
end Get_User_Identifier;
-- ------------------------------
-- Get the connection session used by the user.
-- ------------------------------
function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is
begin
return From.Session;
end Get_Session;
-- ------------------------------
-- Get the connection session identifier used by the user.
-- ------------------------------
function Get_Session_Identifier (From : in Principal) return ADO.Identifier is
begin
return From.Session.Get_Id;
end Get_Session_Identifier;
-- ------------------------------
-- Create a principal for the given user.
-- ------------------------------
function Create (User : in AWA.Users.Models.User_Ref;
Session : in AWA.Users.Models.Session_Ref) return Principal_Access is
Result : constant Principal_Access := new Principal;
begin
Result.User := User;
Result.Session := Session;
return Result;
end Create;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal.
-- ------------------------------
function Get_User_Identifier (From : in Security.Permissions.Principal_Access)
return ADO.Identifier is
use type Security.Permissions.Principal_Access;
begin
if From = null then
return ADO.NO_IDENTIFIER;
elsif not (From.all in Principal'Class) then
return ADO.NO_IDENTIFIER;
else
return Principal'Class (From.all).Get_User_Identifier;
end if;
end Get_User_Identifier;
end AWA.Users.Principals;
|
-----------------------------------------------------------------------
-- awa-users-principals -- User principals
-- 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 AWA.Users.Principals is
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return From.User.Get_Name;
end Get_Name;
-- ------------------------------
-- Returns true if the given role is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Principal;
Role : in Security.Permissions.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal identifier (name)
-- ------------------------------
function Get_Id (From : in Principal) return String is
begin
return From.User.Get_Name;
end Get_Id;
-- ------------------------------
-- Get the user associated with the principal.
-- ------------------------------
function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is
begin
return From.User;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (From : in Principal) return ADO.Identifier is
begin
return From.User.Get_Id;
end Get_User_Identifier;
-- ------------------------------
-- Get the connection session used by the user.
-- ------------------------------
function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is
begin
return From.Session;
end Get_Session;
-- ------------------------------
-- Get the connection session identifier used by the user.
-- ------------------------------
function Get_Session_Identifier (From : in Principal) return ADO.Identifier is
begin
return From.Session.Get_Id;
end Get_Session_Identifier;
-- ------------------------------
-- Create a principal for the given user.
-- ------------------------------
function Create (User : in AWA.Users.Models.User_Ref;
Session : in AWA.Users.Models.Session_Ref) return Principal_Access is
Result : constant Principal_Access := new Principal;
begin
Result.User := User;
Result.Session := Session;
return Result;
end Create;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal.
-- ------------------------------
function Get_User_Identifier (From : in ASF.Principals.Principal_Access)
return ADO.Identifier is
use type ASF.Principals.Principal_Access;
begin
if From = null then
return ADO.NO_IDENTIFIER;
elsif not (From.all in Principal'Class) then
return ADO.NO_IDENTIFIER;
else
return Principal'Class (From.all).Get_User_Identifier;
end if;
end Get_User_Identifier;
end AWA.Users.Principals;
|
Use ASF.Principals definition
|
Use ASF.Principals definition
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0ffbbefddd749b21e0187ab4bc59c2dbd64a1ff7
|
awa/src/awa-events-queues-persistents.adb
|
awa/src/awa-events-queues-persistents.adb
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC renames AWA.Services.Contexts;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Event.Get_Event_Kind);
end Set_Event;
begin
App.Do_Event_Manager (Set_Event'Access);
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
Msg.Set_Entity_Id (Event.Get_Entity_Identifier);
Msg.Set_Entity_Type (Event.Entity_Type);
-- Collect the event parameters in a string and format the result in JSON.
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props));
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name));
Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props);
Event.Set_Entity_Identifier (Msg.Get_Entity_Id);
Event.Entity_Type := Msg.Get_Entity_Type;
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", E, True);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
Log.Info ("Dispatching {0} events", Natural'Image (Count));
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC renames AWA.Services.Contexts;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Event.Get_Event_Kind);
end Set_Event;
begin
App.Do_Event_Manager (Set_Event'Access);
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
Msg.Set_Entity_Id (Event.Get_Entity_Identifier);
Msg.Set_Entity_Type (Event.Entity_Type);
-- Collect the event parameters in a string and format the result in JSON.
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props));
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.SQL.Query;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name));
Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props);
Event.Set_Entity_Identifier (Msg.Get_Entity_Id);
Event.Entity_Type := Msg.Get_Entity_Type;
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", E, True);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Filter ("o.status = 0 AND o.queue_id = :queue ORDER BY o.priority DESC, "
& "o.id ASC LIMIT :max");
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
Log.Info ("Dispatching {0} events", Natural'Image (Count));
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
Update the implementation according to the UML model
|
Update the implementation according to the UML model
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b42831b4014fb76a7f662f6c8d5805be174668cc
|
awa/src/awa-events-configs-reader_config.adb
|
awa/src/awa-events-configs-reader_config.adb
|
-----------------------------------------------------------------------
-- awa-events-configs -- Event configuration
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
package body AWA.Events.Configs.Reader_Config is
procedure Initialize is
begin
Add_Mapping (Mapper, Config'Unchecked_Access);
Config.Manager := Manager;
Config.Context := Context;
Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current);
end Initialize;
end AWA.Events.Configs.Reader_Config;
|
-----------------------------------------------------------------------
-- awa-events-configs -- Event configuration
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Events.Queues;
with AWA.Services.Contexts;
package body AWA.Events.Configs.Reader_Config is
procedure Initialize is
begin
Add_Mapping (Mapper, Config'Unchecked_Access);
Config.Manager := Manager;
Config.Context := Context;
Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current);
end Initialize;
end AWA.Events.Configs.Reader_Config;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ee76c4bf7a9879c8190906c117a24ab24501df3a
|
src/gen-model-projects.ads
|
src/gen-model-projects.ads
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- 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.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
use Ada.Strings.Unbounded;
type Project_Definition;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : Unbounded_String;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : Unbounded_String;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Project_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
-- ------------------------------
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : Unbounded_String;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
use Ada.Strings.Unbounded;
type Project_Definition;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : Unbounded_String;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : Unbounded_String;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
-- Whether this project is a plugin.
Is_Plugin : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Project_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
-- ------------------------------
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : Unbounded_String;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
Add Is_Plugin member to the project definition
|
Add Is_Plugin member to the project definition
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
e2df7b9b01e86ea2d4ffbb842d92ef0858ccac62
|
mat/src/gtk/gtkmatp.adb
|
mat/src/gtk/gtkmatp.adb
|
-----------------------------------------------------------------------
-- gtkmatp -- Gtk MAT application
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Targets.Gtkmat;
with Gtk.Main;
with Gtk.Widget;
procedure GtkMatp is
Main : Gtk.Widget.Gtk_Widget;
Target : MAT.Targets.Gtkmat.Target_Type;
begin
Target.Initialize_Options;
Target.Initialize_Widget (Main);
MAT.Commands.Initialize_Files (Target);
Target.Start;
MAT.Commands.Interactive (Target);
Target.Stop;
Gtk.Main.Main;
end GtkMatp;
|
-----------------------------------------------------------------------
-- gtkmatp -- Gtk MAT application
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Targets.Gtkmat;
with Gtk.Widget;
procedure GtkMatp is
Main : Gtk.Widget.Gtk_Widget;
Target : MAT.Targets.Gtkmat.Target_Type;
begin
Target.Initialize_Options;
Target.Initialize_Widget (Main);
MAT.Commands.Initialize_Files (Target);
Target.Start;
MAT.Commands.Interactive (Target);
Target.Stop;
end GtkMatp;
|
Remove the Gtk main loop
|
Remove the Gtk main loop
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f1f5b3392a12136f69cfb6a5aa461baefef313a8
|
mat/src/mat-readers.adb
|
mat/src/mat-readers.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
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;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Read_Probe (Client : in out Manager_Base;
Msg : in out Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : access MAT.Events.Frame_Info := Client.Frame;
begin
Frame.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.Buffer, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_ID =>
Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Natural (Count) loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
use type MAT.Events.Attribute_Table_Ptr;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
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 Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access,
Client.Frame.all, Msg);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
Frame : Message_Handler;
procedure Add_Handler (Key : in String;
Element : in out Message_Handler) is
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0}", Name);
if Name = "begin" 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.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Message_Handler) is
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 Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("begin", Frame);
end if;
end;
end loop;
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
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;
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
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;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Read_Probe (Client : in out Manager_Base;
Msg : in out Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : access MAT.Events.Frame_Info := Client.Frame;
begin
Frame.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.Buffer, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_ID =>
Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Natural (Count) loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
use type MAT.Events.Attribute_Table_Ptr;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
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 Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access,
Client.Frame.all, Msg);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
Frame : Message_Handler;
procedure Add_Handler (Key : in String;
Element : in out Message_Handler) is
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0}", Name);
if Name = "begin" 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.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Message_Handler) is
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 Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("begin", Frame);
end if;
end;
end loop;
if Reader_Maps.Has_Element (Pos) then
Client.Readers.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 Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
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;
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Readers;
|
Implement and use the Read_Event_Definitions procedure
|
Implement and use the Read_Event_Definitions procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
05fd8a546f780504dab6f8aaf26895b34f638967
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
with Wiki.Streams;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Doc : in out Wiki.Nodes.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Nodes.Document);
private
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Chain;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
with Wiki.Streams;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Doc : in out Wiki.Nodes.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Nodes.Document);
private
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Chain;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
end Wiki.Parsers;
|
Move the CR constant to Wiki.Helpers
|
Move the CR constant to Wiki.Helpers
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
712b3f9c6fdeebab69cc5ae7e2ad1207ec10d981
|
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_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;
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_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;
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 To_Char function
|
Declare the To_Char function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bf8dc5d9e60f6c32caac7e42d1512d567ebb65a7
|
regtests/wiki-tests.adb
|
regtests/wiki-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Variables;
with Wiki.Plugins.Templates;
with Wiki.Plugins.Conditions;
with Wiki.Plugins.Variables;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin;
Variables : aliased Wiki.Plugins.Variables.Variable_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record;
-- Find a plugin knowing its name.
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access;
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is
pragma Unreferenced (Factory);
begin
if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then
return Condition'Unchecked_Access;
elsif Name = "set" then
return Variables'Unchecked_Access;
else
return Template.Find (Name);
end if;
end Find;
Local_Factory : aliased Test_Factory;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
Condition.Append ("public", "");
Condition.Append ("user", "admin");
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Add_Filter (Var_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML then
declare
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name));
end;
elsif T.Is_Html then
declare
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render HTML " & To_String (T.Name));
end;
else
declare
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Text " & To_String (T.Name));
end;
end if;
end;
Input.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Autolink;
with Wiki.Filters.Variables;
with Wiki.Plugins.Templates;
with Wiki.Plugins.Conditions;
with Wiki.Plugins.Variables;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter;
Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin;
Variables : aliased Wiki.Plugins.Variables.Variable_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record;
-- Find a plugin knowing its name.
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access;
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is
pragma Unreferenced (Factory);
begin
if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then
return Condition'Unchecked_Access;
elsif Name = "set" then
return Variables'Unchecked_Access;
else
return Template.Find (Name);
end if;
end Find;
Local_Factory : aliased Test_Factory;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
Condition.Append ("public", "");
Condition.Append ("user", "admin");
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Auto_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Add_Filter (Var_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML then
declare
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name));
end;
elsif T.Is_Html then
declare
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render HTML " & To_String (T.Name));
end;
else
declare
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Text " & To_String (T.Name));
end;
end if;
end;
Input.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
Add the Autolink filter when running the unit tests
|
Add the Autolink filter when running the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c3201315c9e2781e8abca5ec7e28feda115bae41
|
src/gen-artifacts-distribs.ads
|
src/gen-artifacts-distribs.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs -- Artifact for distributions
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
with GNAT.Regpat;
with DOM.Core;
with Gen.Model.Packages;
with Util.Log;
-- The <b>Gen.Artifacts.Distribs</b> package is an artifact for the generation of
-- application distributions.
--
-- 1/ The package.xml file contains a set of rules which describe how to build the distribution.
-- This file is read and distribution rules are collected in the <b>Rules</b> artifact.
--
-- 2/ The list of source paths to scan is obtained by looking at the GNAT project files
-- and looking at components which have a <b>dynamo.xml</b> configuration file.
--
-- 3/ The source paths are then scanned and a complete tree of source files is created
-- in the <b>Trees</b> artifact member.
--
-- 4/ The source paths are matched against the distribution rules and each distribution rule
-- is filled with the source files that they match.
--
-- 5/ The distribution rules are executed in the order defined in the <b>package.xml</b> file.
-- Each distribution rule can have its own way to make the distribution for the set of
-- files that matched the rule definition. A distribution rule can copy the file, another
-- can concatenate the source files, another can do some transformation on the source files
-- and prepare it for the distribution.
--
package Gen.Artifacts.Distribs is
-- ------------------------------
-- Distribution 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);
private
type Directory_List;
type Directory_List_Access is access all Directory_List;
-- A <b>File_Record</b> refers to a source file that must be processed by a distribution
-- rule. It is linked to the directory which contains it through the <b>Dir</b> member.
-- The <b>Name</b> refers to the file name part.
type File_Record (Length : Natural) is record
Dir : Directory_List_Access;
Name : String (1 .. Length);
end record;
package File_Record_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => File_Record);
subtype File_Vector is File_Record_Vectors.Vector;
subtype File_Cursor is File_Record_Vectors.Cursor;
-- Get the first source path from the list.
function Get_First_Path (From : in File_Vector) return String;
-- The file tree represents the target distribution tree that must be built.
-- Each key represent a target file and it is associated with a <b>File_Vector</b> which
-- represents the list of source files that must be used to build the target.
package File_Tree is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => File_Vector,
"<" => "<",
"=" => File_Record_Vectors."=");
package Directory_List_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_List_Access);
-- The <b>Directory_List<b> describes the content of a source directory.
type Directory_List (Length : Positive;
Path_Length : Natural) is record
Files : File_Record_Vectors.Vector;
Directories : Directory_List_Vector.Vector;
Rel_Pos : Positive := 1;
Name : String (1 .. Length);
Path : String (1 .. Path_Length);
end record;
-- Get the relative path of the directory.
function Get_Relative_Path (Dir : in Directory_List) return String;
-- Strip the base part of the path
function Get_Strip_Path (Base : in String;
Path : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return GNAT.Regpat.Pattern_Matcher;
-- Scan the directory whose root path is <b>Path</b> and with the relative path
-- <b>Rel_Path</b> and build in <b>Dir</b> the list of files and directories.
procedure Scan (Path : in String;
Rel_Path : in String;
Dir : in Directory_List_Access);
type Match_Rule is record
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Match_Rule_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Match_Rule);
-- ------------------------------
-- Distribution rule
-- ------------------------------
-- The <b>Distrib_Rule</b> represents a distribution rule that must be executed on
-- a given file or set of files.
type Distrib_Rule is abstract tagged record
Dir : Ada.Strings.Unbounded.Unbounded_String;
Matches : Match_Rule_Vector.Vector;
Files : File_Tree.Map;
Level : Util.Log.Level_Type := Util.Log.DEBUG_LEVEL;
end record;
type Distrib_Rule_Access is access all Distrib_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
function Get_Install_Name (Rule : in Distrib_Rule) return String is abstract;
-- Install the file <b>File</b> according to the distribution rule.
procedure Install (Rule : in Distrib_Rule;
Target : in String;
File : in File_Vector;
Context : in out Generator'Class) is abstract;
-- Scan the directory tree whose root is defined by <b>Dir</b> and find the files
-- that match the current rule.
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List);
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List;
Base_Dir : in String;
Pattern : in String);
procedure Execute (Rule : in out Distrib_Rule;
Path : in String;
Context : in out Generator'Class);
-- Get the target path associate with the given source file for the distribution rule.
function Get_Target_Path (Rule : in Distrib_Rule;
Base : in String;
File : in File_Record) return String;
-- Get the source path of the file.
function Get_Source_Path (Rule : in Distrib_Rule;
File : in File_Record) return String;
-- Add the file to be processed by the distribution rule. The file has a relative
-- path represented by <b>Path</b>. The path is relative from the base directory
-- specified in <b>Base_Dir</b>.
procedure Add_Source_File (Rule : in out Distrib_Rule;
Path : in String;
File : in File_Record);
-- Create a distribution rule identified by <b>Kind</b>.
-- The distribution rule is configured according to the DOM tree whose node is <b>Node</b>.
function Create_Rule (Kind : in String;
Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- A list of rules that define how to build the distribution.
package Distrib_Rule_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Distrib_Rule_Access);
type Artifact is new Gen.Artifacts.Artifact with record
Rules : Distrib_Rule_Vectors.Vector;
Trees : Directory_List_Vector.Vector;
end record;
end Gen.Artifacts.Distribs;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs -- Artifact for distributions
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
with GNAT.Regpat;
with DOM.Core;
with Gen.Model.Packages;
with Util.Log;
-- The <b>Gen.Artifacts.Distribs</b> package is an artifact for the generation of
-- application distributions.
--
-- 1/ The package.xml file contains a set of rules which describe how to build the distribution.
-- This file is read and distribution rules are collected in the <b>Rules</b> artifact.
--
-- 2/ The list of source paths to scan is obtained by looking at the GNAT project files
-- and looking at components which have a <b>dynamo.xml</b> configuration file.
--
-- 3/ The source paths are then scanned and a complete tree of source files is created
-- in the <b>Trees</b> artifact member.
--
-- 4/ The source paths are matched against the distribution rules and each distribution rule
-- is filled with the source files that they match.
--
-- 5/ The distribution rules are executed in the order defined in the <b>package.xml</b> file.
-- Each distribution rule can have its own way to make the distribution for the set of
-- files that matched the rule definition. A distribution rule can copy the file, another
-- can concatenate the source files, another can do some transformation on the source files
-- and prepare it for the distribution.
--
package Gen.Artifacts.Distribs is
-- ------------------------------
-- Distribution 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);
private
type Directory_List;
type Directory_List_Access is access all Directory_List;
-- A <b>File_Record</b> refers to a source file that must be processed by a distribution
-- rule. It is linked to the directory which contains it through the <b>Dir</b> member.
-- The <b>Name</b> refers to the file name part.
type File_Record (Length : Natural) is record
Dir : Directory_List_Access;
Name : String (1 .. Length);
end record;
package File_Record_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => File_Record);
subtype File_Vector is File_Record_Vectors.Vector;
subtype File_Cursor is File_Record_Vectors.Cursor;
-- Get the first source path from the list.
function Get_Source_Path (From : in File_Vector;
Use_First_File : in Boolean := False) return String;
-- The file tree represents the target distribution tree that must be built.
-- Each key represent a target file and it is associated with a <b>File_Vector</b> which
-- represents the list of source files that must be used to build the target.
package File_Tree is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => File_Vector,
"<" => "<",
"=" => File_Record_Vectors."=");
package Directory_List_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_List_Access);
-- The <b>Directory_List<b> describes the content of a source directory.
type Directory_List (Length : Positive;
Path_Length : Natural) is record
Files : File_Record_Vectors.Vector;
Directories : Directory_List_Vector.Vector;
Rel_Pos : Positive := 1;
Name : String (1 .. Length);
Path : String (1 .. Path_Length);
end record;
-- Get the relative path of the directory.
function Get_Relative_Path (Dir : in Directory_List) return String;
-- Strip the base part of the path
function Get_Strip_Path (Base : in String;
Path : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return GNAT.Regpat.Pattern_Matcher;
-- Scan the directory whose root path is <b>Path</b> and with the relative path
-- <b>Rel_Path</b> and build in <b>Dir</b> the list of files and directories.
procedure Scan (Path : in String;
Rel_Path : in String;
Dir : in Directory_List_Access);
type Match_Rule is record
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Match_Rule_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Match_Rule);
-- ------------------------------
-- Distribution rule
-- ------------------------------
-- The <b>Distrib_Rule</b> represents a distribution rule that must be executed on
-- a given file or set of files.
type Distrib_Rule is abstract tagged record
Dir : Ada.Strings.Unbounded.Unbounded_String;
Matches : Match_Rule_Vector.Vector;
Files : File_Tree.Map;
Level : Util.Log.Level_Type := Util.Log.DEBUG_LEVEL;
end record;
type Distrib_Rule_Access is access all Distrib_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
function Get_Install_Name (Rule : in Distrib_Rule) return String is abstract;
-- Install the file <b>File</b> according to the distribution rule.
procedure Install (Rule : in Distrib_Rule;
Target : in String;
File : in File_Vector;
Context : in out Generator'Class) is abstract;
-- Scan the directory tree whose root is defined by <b>Dir</b> and find the files
-- that match the current rule.
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List);
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List;
Base_Dir : in String;
Pattern : in String);
procedure Execute (Rule : in out Distrib_Rule;
Path : in String;
Context : in out Generator'Class);
-- Get the target path associate with the given source file for the distribution rule.
function Get_Target_Path (Rule : in Distrib_Rule;
Base : in String;
File : in File_Record) return String;
-- Get the source path of the file.
function Get_Source_Path (Rule : in Distrib_Rule;
File : in File_Record) return String;
-- Add the file to be processed by the distribution rule. The file has a relative
-- path represented by <b>Path</b>. The path is relative from the base directory
-- specified in <b>Base_Dir</b>.
procedure Add_Source_File (Rule : in out Distrib_Rule;
Path : in String;
File : in File_Record);
-- Create a distribution rule identified by <b>Kind</b>.
-- The distribution rule is configured according to the DOM tree whose node is <b>Node</b>.
function Create_Rule (Kind : in String;
Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- A list of rules that define how to build the distribution.
package Distrib_Rule_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Distrib_Rule_Access);
type Artifact is new Gen.Artifacts.Artifact with record
Rules : Distrib_Rule_Vectors.Vector;
Trees : Directory_List_Vector.Vector;
end record;
end Gen.Artifacts.Distribs;
|
Rename Get_First_Path into Get_Source_Path and allow to retrieve either the first or last file
|
Rename Get_First_Path into Get_Source_Path and allow to retrieve either the first or last file
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
d66e7b5ce1bcea52c018291d540696803a565a5b
|
samples/render.adb
|
samples/render.adb
|
-----------------------------------------------------------------------
-- render -- Wiki rendering example
-- 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.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with GNAT.Command_Line;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Filters.TOC;
with Wiki.Filters.Html;
with Wiki.Plugins.Templates;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
procedure Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String);
procedure Render_Text (Doc : in out Wiki.Documents.Document);
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text");
Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-d] [-c] [-s style] {wiki-file}");
Ada.Text_IO.Put_Line (" -t Render to text only");
Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content");
Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content");
Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content");
Ada.Text_IO.Put_Line (" -g Render a Google wiki content");
Ada.Text_IO.Put_Line (" -c Render a Creole wiki content");
Ada.Text_IO.Put_Line (" -s style Use the CSS style file");
end Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String) is
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
if Length (Style) > 0 then
Output.Start_Element ("html");
Output.Start_Element ("head");
Output.Start_Element ("link");
Output.Write_Attribute ("type", "text/css");
Output.Write_Attribute ("rel", "stylesheet");
Output.Write_Attribute ("href", To_String (Style));
Output.End_Element ("link");
Output.End_Element ("head");
Output.Start_Element ("body");
end if;
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
if Length (Style) > 0 then
Output.End_Element ("body");
Output.End_Element ("html");
end if;
end Render_Html;
procedure Render_Text (Doc : in out Wiki.Documents.Document) is
Output : aliased Wiki.Streams.Text_IO.File_Output_Stream;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
end Render_Text;
Count : Natural := 0;
Html_Mode : Boolean := True;
Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN;
Style : Unbounded_String;
begin
loop
case Getopt ("m M d c g t s:") is
when 'm' =>
Syntax := Wiki.SYNTAX_MARKDOWN;
when 'M' =>
Syntax := Wiki.SYNTAX_MEDIA_WIKI;
when 'c' =>
Syntax := Wiki.SYNTAX_CREOLE;
when 'd' =>
Syntax := Wiki.SYNTAX_DOTCLEAR;
when 'g' =>
Syntax := Wiki.SYNTAX_GOOGLE;
when 't' =>
Html_Mode := False;
when 's' =>
Style := To_Unbounded_String (Parameter);
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
Template.Set_Template_Path (".");
-- Open the file and parse it (assume UTF-8).
Input.Open (Name, "WCEM=8");
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Input'Unchecked_Access, Doc);
-- Render the document in text or HTML.
if Html_Mode then
Render_Html (Doc, Style);
else
Render_Text (Doc);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Render;
|
-----------------------------------------------------------------------
-- render -- Wiki rendering example
-- 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.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Directories;
with GNAT.Command_Line;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Filters.TOC;
with Wiki.Filters.Html;
with Wiki.Plugins.Templates;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
procedure Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String);
procedure Render_Text (Doc : in out Wiki.Documents.Document);
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text");
Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-d] [-c] [-s style] {wiki-file}");
Ada.Text_IO.Put_Line (" -t Render to text only");
Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content");
Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content");
Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content");
Ada.Text_IO.Put_Line (" -g Render a Google wiki content");
Ada.Text_IO.Put_Line (" -c Render a Creole wiki content");
Ada.Text_IO.Put_Line (" -s style Use the CSS style file");
end Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String) is
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
if Length (Style) > 0 then
Output.Start_Element ("html");
Output.Start_Element ("head");
Output.Start_Element ("link");
Output.Write_Attribute ("type", "text/css");
Output.Write_Attribute ("rel", "stylesheet");
Output.Write_Attribute ("href", To_String (Style));
Output.End_Element ("link");
Output.End_Element ("head");
Output.Start_Element ("body");
end if;
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
if Length (Style) > 0 then
Output.End_Element ("body");
Output.End_Element ("html");
end if;
end Render_Html;
procedure Render_Text (Doc : in out Wiki.Documents.Document) is
Output : aliased Wiki.Streams.Text_IO.File_Output_Stream;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
end Render_Text;
Count : Natural := 0;
Html_Mode : Boolean := True;
Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN;
Style : Unbounded_String;
begin
loop
case Getopt ("m M d c g t s:") is
when 'm' =>
Syntax := Wiki.SYNTAX_MARKDOWN;
when 'M' =>
Syntax := Wiki.SYNTAX_MEDIA_WIKI;
when 'c' =>
Syntax := Wiki.SYNTAX_CREOLE;
when 'd' =>
Syntax := Wiki.SYNTAX_DOTCLEAR;
when 'g' =>
Syntax := Wiki.SYNTAX_GOOGLE;
when 't' =>
Html_Mode := False;
when 's' =>
Style := To_Unbounded_String (Parameter);
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name));
-- Open the file and parse it (assume UTF-8).
Input.Open (Name, "WCEM=8");
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Input'Unchecked_Access, Doc);
-- Render the document in text or HTML.
if Html_Mode then
Render_Html (Doc, Style);
else
Render_Text (Doc);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Render;
|
Set the template expander to use the same directory as the wiki source file
|
Set the template expander to use the same directory as the wiki source file
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
250a65f77b90a785abc6387ec05d22b2fab2674b
|
src/asf-lifecycles-restore.adb
|
src/asf-lifecycles-restore.adb
|
-----------------------------------------------------------------------
-- asf-lifecycles-restore -- Restore view phase
-- Copyright (C) 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with ASF.Applications.Main;
with ASF.Components.Root;
with ASF.Requests;
with Util.Log.Loggers;
package body ASF.Lifecycles.Restore is
use Ada.Exceptions;
use Util.Log;
use ASF.Applications;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Lifecycles.Restore");
-- ------------------------------
-- Initialize the phase controller.
-- ------------------------------
overriding
procedure Initialize (Controller : in out Restore_Controller;
App : access ASF.Applications.Main.Application'Class) is
begin
Controller.View_Handler := App.Get_View_Handler;
end Initialize;
-- ------------------------------
-- Execute the restore view phase.
-- ------------------------------
overriding
procedure Execute (Controller : in Restore_Controller;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use ASF.Components;
Req : constant ASF.Requests.Request_Access := Context.Get_Request;
Page : constant String := Req.Get_Servlet_Path;
View : Components.Root.UIViewRoot;
begin
Controller.View_Handler.Restore_View (Page, Context, View);
Context.Set_View_Root (View);
-- If this is not a postback, check for view parameters.
if Req.Get_Method = "GET" then
-- We need to process the ASF lifecycle towards the meta data component tree.
-- This allows some Ada beans to be initialized from the request parameters
-- and have some component actions called on the http GET (See <f:viewActions)).
Components.Root.Set_Meta (View);
-- If the view has no meta data, render the response immediately.
if not Components.Root.Has_Meta (View) then
Context.Render_Response;
end if;
end if;
exception
when E : others =>
Log.Error ("Error when restoring view {0}: {1}: {2}", Page,
Exception_Name (E), Exception_Message (E));
raise;
end Execute;
end ASF.Lifecycles.Restore;
|
-----------------------------------------------------------------------
-- asf-lifecycles-restore -- Restore view phase
-- Copyright (C) 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with ASF.Applications.Main;
with ASF.Components.Root;
with ASF.Requests;
with Util.Log.Loggers;
package body ASF.Lifecycles.Restore is
use Ada.Exceptions;
use Util.Log;
use ASF.Applications;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Lifecycles.Restore");
-- ------------------------------
-- Initialize the phase controller.
-- ------------------------------
overriding
procedure Initialize (Controller : in out Restore_Controller;
App : access ASF.Applications.Main.Application'Class) is
begin
Controller.View_Handler := App.Get_View_Handler;
end Initialize;
-- ------------------------------
-- Execute the restore view phase.
-- ------------------------------
overriding
procedure Execute (Controller : in Restore_Controller;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use ASF.Components;
Req : constant ASF.Requests.Request_Access := Context.Get_Request;
Page : constant String := Context.Get_View_Name;
View : Components.Root.UIViewRoot;
begin
Controller.View_Handler.Restore_View (Page, Context, View);
Context.Set_View_Root (View);
-- If this is not a postback, check for view parameters.
if Req.Get_Method = "GET" then
-- We need to process the ASF lifecycle towards the meta data component tree.
-- This allows some Ada beans to be initialized from the request parameters
-- and have some component actions called on the http GET (See <f:viewActions)).
Components.Root.Set_Meta (View);
-- If the view has no meta data, render the response immediately.
if not Components.Root.Has_Meta (View) then
Context.Render_Response;
end if;
end if;
exception
when E : others =>
Log.Error ("Error when restoring view {0}: {1}: {2}", Page,
Exception_Name (E), Exception_Message (E));
raise;
end Execute;
end ASF.Lifecycles.Restore;
|
Use Get_View_Name to get the view name
|
Use Get_View_Name to get the view name
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
348b40e89a8f5bd8b417524bbc8128212f180f84
|
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 Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Readers.Streams.Sockets;
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;
Events : MAT.Events.Targets.Target_Events_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Readers.Reader_List_Type with 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.
overriding
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;
-- 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));
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- 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);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out 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 new Ada.Finalization.Limited_Controlled
and MAT.Readers.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_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 Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Readers.Streams.Sockets;
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 received.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Print the events as they are received.
Print_Events : 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;
Events : MAT.Events.Targets.Target_Events_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Readers.Reader_List_Type with 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.
overriding
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;
-- 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));
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- 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);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out 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 new Ada.Finalization.Limited_Controlled
and MAT.Readers.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
end MAT.Targets;
|
Add Print_Events in Options_Type
|
Add Print_Events in Options_Type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1c765718b1dea2d51cc3ad0e6870366afa0d7e00
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
Check_Parse ("[{ ""person"":""\u2ABF""}]");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
-- ------------------------------
-- Test reading a JSON content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass01.json");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
Item : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (Util.Beans.Objects.Is_Array (Root), "Root object is an array");
Value := Util.Beans.Objects.Get_Value (Root, 1);
Util.Tests.Assert_Equals (T, "JSON Test Pattern pass1",
Util.Beans.Objects.To_String (Value), "Invalid first element");
Value := Util.Beans.Objects.Get_Value (Root, 4);
T.Assert (Util.Beans.Objects.Is_Array (Value), "Element 4 should be an empty array");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.Get_Count (Value), "Invalid array");
Value := Util.Beans.Objects.Get_Value (Root, 8);
T.Assert (Util.Beans.Objects.Is_Null (Value), "Element 8 should be null");
Value := Util.Beans.Objects.Get_Value (Root, 9);
T.Assert (not Util.Beans.Objects.Is_Null (Value), "Element 9 should not be null");
Item := Util.Beans.Objects.Get_Value (Value, "integer");
Util.Tests.Assert_Equals (T, 1234567890, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value");
Item := Util.Beans.Objects.Get_Value (Value, "zero");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (0)");
Item := Util.Beans.Objects.Get_Value (Value, "one");
Util.Tests.Assert_Equals (T, 1, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (1)");
Item := Util.Beans.Objects.Get_Value (Value, "true");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value true should be a boolean");
T.Assert (Util.Beans.Objects.To_Boolean (Item),
"The value true should be... true!");
Item := Util.Beans.Objects.Get_Value (Value, "false");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value false should be a boolean");
T.Assert (not Util.Beans.Objects.To_Boolean (Item),
"The value false should be... false!");
Item := Util.Beans.Objects.Get_Value (Value, " s p a c e d ");
T.Assert (Is_Array (Item), "The value should be an array");
for I in 1 .. 7 loop
Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (Item, I)),
"Invalid array value at " & Integer'Image (I));
end loop;
end Test_Read;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write (Simple)",
Test_Simple_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
Check_Parse ("[{ ""person"":""\u2ABF""}]");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
-- ------------------------------
-- Test the JSON output stream generation (simple JSON documents).
-- ------------------------------
procedure Test_Simple_Output (T : in out Test) is
function Get_Array return String;
function Get_Struct return String;
function Get_Named_Struct return String;
function Get_Integer return String;
function Get_String return String;
function Get_Array return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Array ("");
Stream.Write_Entity ("", 23);
Stream.Write_Entity ("", 45);
Stream.End_Array ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Array;
function Get_Struct return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("");
Stream.Write_Entity ("age", 23);
Stream.Write_Entity ("id", 45);
Stream.End_Entity ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Struct;
function Get_Named_Struct return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("name");
Stream.Write_Entity ("age", 23);
Stream.Write_Entity ("id", 45);
Stream.End_Entity ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Named_Struct;
function Get_Integer return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Write_Entity ("", 23);
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Integer;
function Get_String return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Write_Entity ("", "test");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_String;
A1 : constant String := Get_Array;
S1 : constant String := Get_Struct;
S2 : constant String := Get_Named_Struct;
I1 : constant String := Get_Integer;
S3 : constant String := Get_String;
begin
Log.Error ("Array: {0}", A1);
Util.Tests.Assert_Equals (T, "[ 23, 45]", A1,
"Invalid JSON array");
Log.Error ("Struct: {0}", S1);
Util.Tests.Assert_Equals (T, "{""age"": 23,""id"": 45}", S1,
"Invalid JSON struct");
Log.Error ("Struct: {0}", S2);
Util.Tests.Assert_Equals (T, "{""name"":{""age"": 23,""id"": 45}}", S2,
"Invalid JSON struct");
Log.Error ("Struct: {0}", I1);
Util.Tests.Assert_Equals (T, " 23", I1,
"Invalid JSON struct");
Log.Error ("Struct: {0}", S3);
Util.Tests.Assert_Equals (T, """test""", S3,
"Invalid JSON struct");
end Test_Simple_Output;
-- ------------------------------
-- Test reading a JSON content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass01.json");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
Item : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (Util.Beans.Objects.Is_Array (Root), "Root object is an array");
Value := Util.Beans.Objects.Get_Value (Root, 1);
Util.Tests.Assert_Equals (T, "JSON Test Pattern pass1",
Util.Beans.Objects.To_String (Value), "Invalid first element");
Value := Util.Beans.Objects.Get_Value (Root, 4);
T.Assert (Util.Beans.Objects.Is_Array (Value), "Element 4 should be an empty array");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.Get_Count (Value), "Invalid array");
Value := Util.Beans.Objects.Get_Value (Root, 8);
T.Assert (Util.Beans.Objects.Is_Null (Value), "Element 8 should be null");
Value := Util.Beans.Objects.Get_Value (Root, 9);
T.Assert (not Util.Beans.Objects.Is_Null (Value), "Element 9 should not be null");
Item := Util.Beans.Objects.Get_Value (Value, "integer");
Util.Tests.Assert_Equals (T, 1234567890, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value");
Item := Util.Beans.Objects.Get_Value (Value, "zero");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (0)");
Item := Util.Beans.Objects.Get_Value (Value, "one");
Util.Tests.Assert_Equals (T, 1, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (1)");
Item := Util.Beans.Objects.Get_Value (Value, "true");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value true should be a boolean");
T.Assert (Util.Beans.Objects.To_Boolean (Item),
"The value true should be... true!");
Item := Util.Beans.Objects.Get_Value (Value, "false");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value false should be a boolean");
T.Assert (not Util.Beans.Objects.To_Boolean (Item),
"The value false should be... false!");
Item := Util.Beans.Objects.Get_Value (Value, " s p a c e d ");
T.Assert (Is_Array (Item), "The value should be an array");
for I in 1 .. 7 loop
Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (Item, I)),
"Invalid array value at " & Integer'Image (I));
end loop;
end Test_Read;
end Util.Serialize.IO.JSON.Tests;
|
Implement the Test_Simple_Output procedure - register the new test - test the JSON stream generation with very simple and basic forms
|
Implement the Test_Simple_Output procedure
- register the new test
- test the JSON stream generation with very simple and basic forms
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b00b3fc640b80a02f29906bffa97db79e551ffa3
|
regtests/security-oauth-servers-tests.adb
|
regtests/security-oauth-servers-tests.adb
|
-----------------------------------------------------------------------
-- 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 Ada.Strings.Fixed;
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Sets;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- 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) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
Auth : Principal_Access;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20, "Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null, "Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name, "Invalid user name in the principal");
-- Verify the access token.
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant, "Expecting Revoked_Grant for the authenticate");
end Test_Token_Password;
end Security.OAuth.Servers.Tests;
|
-----------------------------------------------------------------------
-- 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 Ada.Strings.Fixed;
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Sets;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- 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) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
Auth : Principal_Access;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20, "Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null, "Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name, "Invalid user name in the principal");
-- Verify the access token.
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant, "Expecting Revoked_Grant for the authenticate");
-- Change application token expiration time to 1 second.
App.Expire_Timeout := 1.0;
Apps.Add_Application (App);
-- Make the access token.
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct");
-- Verify the access token.
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
-- Wait for the token to expire.
delay 2.0;
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Expired_Grant, "Expecting Expired when the access token is checked");
end Test_Token_Password;
end Security.OAuth.Servers.Tests;
|
Add a test to check the token expiration
|
Add a test to check the token expiration
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
4c7bcdc28da85ca5ea0a77f432c2438d4cd05359
|
src/sys/streams/util-streams-buffered.ads
|
src/sys/streams/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Unchecked_Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive);
-- Initialize the stream from the buffer created for an output stream.
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Output_Buffer_Stream);
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : access Input_Stream'Class;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Unchecked_Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Stream : in out Output_Buffer_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive);
-- Initialize the stream from the buffer created for an output stream.
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : access Input_Stream'Class;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
Update Output_Buffer_Stream to make the Finalize visible so that we can override it in the buffered encoder implementation
|
Update Output_Buffer_Stream to make the Finalize visible so that we can override
it in the buffered encoder implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
785892a3d4d850539fad3a57a04a234d4bb3601d
|
src/asf-components-widgets-likes.adb
|
src/asf-components-widgets-likes.adb
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
-- GNAT bug, the with clause is necessary to call Get_Global on the application.
pragma Warnings (Off, "*is not referenced");
with ASF.Applications.Main;
pragma Warnings (On, "*is not referenced");
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FB_SEND_ATTR : aliased constant String := "data-send";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
G_ANNOTATION_ATTR : aliased constant String := "data-annotation";
G_WIDTH_ATTR : aliased constant String := "data-width";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWITTER_NAME : aliased constant String := "twitter";
TWITTER_GENERATOR : aliased Twitter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;js.async=true;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=");
declare
App_Id : constant String
:= Context.Get_Application.Get_Config (P_Facebook_App_Id.P);
begin
if App_Id'Length = 0 then
UI.Log_Error ("The facebook client application id is empty");
UI.Log_Error ("Please, configure the '{0}' property "
& "in the application", P_Facebook_App_Id.PARAM_NAME);
else
Writer.Queue_Script (App_Id);
end if;
end;
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Tweeter like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Writer : constant Contexts.Writer.Response_Writer_Access
:= Context.Get_Response_Writer;
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
Style : constant String := UI.Get_Attribute ("style", Context, "");
Class : constant String := UI.Get_Attribute ("styleClass", Context, "");
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Writer.Start_Element ("div");
if Style'Length > 0 then
Writer.Write_Attribute ("style", Style);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
Generators (I).Generator.Render_Like (UI, Href, Context);
Writer.End_Element ("div");
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
-- GNAT bug, the with clause is necessary to call Get_Global on the application.
pragma Warnings (Off, "*is not referenced");
with ASF.Applications.Main;
pragma Warnings (On, "*is not referenced");
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FB_SEND_ATTR : aliased constant String := "data-send";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
TW_COUNTURL_ATTR : aliased constant String := "data-counturl";
TW_TEXT_ATTR : aliased constant String := "data-text";
TW_RELATED_ATTR : aliased constant String := "data-related";
TW_LANG_ATTR : aliased constant String := "data-lang";
TW_HASHTAGS_ATTR : aliased constant String := "data-hashtags";
G_ANNOTATION_ATTR : aliased constant String := "data-annotation";
G_WIDTH_ATTR : aliased constant String := "data-width";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWITTER_NAME : aliased constant String := "twitter";
TWITTER_GENERATOR : aliased Twitter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;js.async=true;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=");
declare
App_Id : constant String
:= Context.Get_Application.Get_Config (P_Facebook_App_Id.P);
begin
if App_Id'Length = 0 then
UI.Log_Error ("The facebook client application id is empty");
UI.Log_Error ("Please, configure the '{0}' property "
& "in the application", P_Facebook_App_Id.PARAM_NAME);
else
Writer.Queue_Script (App_Id);
end if;
end;
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Tweeter like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Writer : constant Contexts.Writer.Response_Writer_Access
:= Context.Get_Response_Writer;
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
Style : constant String := UI.Get_Attribute ("style", Context, "");
Class : constant String := UI.Get_Attribute ("styleClass", Context, "");
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Writer.Start_Element ("div");
if Style'Length > 0 then
Writer.Write_Attribute ("style", Style);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
Generators (I).Generator.Render_Like (UI, Href, Context);
Writer.End_Element ("div");
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNTURL_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_TEXT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_RELATED_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_LANG_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_HASHTAGS_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
Add several Twitter attributes for the Tweet button
|
Add several Twitter attributes for the Tweet button
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
70fee9f921a8431e52e2ff116334fed5b98625c1
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
pragma Unreferenced (Realm);
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
pragma Unreferenced (Realm, OP);
begin
Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128));
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
pragma Unreferenced (Realm);
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
pragma Unreferenced (Realm, OP);
begin
Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128));
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.STATE);
Code : constant String := Request.Get_Parameter (Security.OAuth.CODE);
Error : constant String := Request.Get_Parameter (Security.OAuth.ERROR_DESCRIPTION);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
46f4ba9290eabc218d07360522f5735ffbfb68bc
|
awa/src/awa.ads
|
awa/src/awa.ads
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package AWA is
pragma Pure;
-- Library SVN identification
SVN_URL : constant String := "$HeadURL: file:///opt/repository/svn/ada/awa/trunk/src/awa.ads $";
-- Revision used (must run 'make version' to update)
SVN_REV : constant String := "$Rev: 318 $";
end AWA;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
--
-- @include awa.xml
package AWA is
pragma Pure;
-- Library SVN identification
SVN_URL : constant String := "$HeadURL: file:///opt/repository/svn/ada/awa/trunk/src/awa.ads $";
-- Revision used (must run 'make version' to update)
SVN_REV : constant String := "$Rev: 318 $";
end AWA;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5328283179bdd5bc3565a0abf53c8ff8005acaaf
|
samples/gperfhash.adb
|
samples/gperfhash.adb
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
if Ignore_Case and I >= 6 and I <= 16 then
if I = 6 then
Generate_Char_Position;
end if;
else
Put_Line (File, L);
end if;
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
Put_Line (File, " H : constant Natural := Hash (S);");
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = "
& "Util.Strings.Transforms.To_Upper_Case (S);");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
Ada.Command_Line.Set_Exit_Status (1);
return;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
end Gperfhash;
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
--
-- Usage: gperfhash [-i] [-p package] keyword-file
--
-- -i Generate a perfect hash which ignores the case
-- -p package Use <b>package</b> as the name of package (default is <b>gphash</b>)
-- keyword-file The file which contains the keywords, one keyword on each line
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
-- Re-generate the char position table to ignore the case.
procedure Generate_Char_Position;
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
-- ------------------------------
-- Re-generate the char position table to ignore the case.
-- ------------------------------
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
-- Replace the char position table by ours. The lower case letter are just
-- mapped to the corresponding upper case letter.
if Ignore_Case and I >= 6 and I <= 16 then
if I = 6 then
Generate_Char_Position;
end if;
else
Put_Line (File, L);
end if;
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
Put_Line (File, " H : constant Natural := Hash (S);");
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = "
& "Util.Strings.Transforms.To_Upper_Case (S);");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
raise GNAT.Command_Line.Invalid_Switch;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read the keyword file.");
Ada.Command_Line.Set_Exit_Status (1);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
Log.Error ("-i Generate a perfect hash which ignores the case");
Log.Error ("-p package Use 'package' as the name of package (default is 'gphash')");
Log.Error ("keyword-file The file which contains the keywords, one keyword on each line");
Ada.Command_Line.Set_Exit_Status (1);
end Gperfhash;
|
Add some error messages
|
Add some error messages
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
7a4fc7f9e30bf9d12c6548bb5c5ea6b7121858f8
|
mat/src/mat-commands.adb
|
mat/src/mat-commands.adb
|
-----------------------------------------------------------------------
-- mat-interp -- Command interpreter
-- 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.Strings;
with Util.Log.Loggers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Bfd;
with MAT.Types;
with MAT.Readers.Files;
with MAT.Memory.Tools;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Expressions;
with MAT.Frames;
with MAT.Frames.Print;
with MAT.Consoles;
package body MAT.Commands is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands");
package Command_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Command_Handler,
Equivalent_Keys => "=",
Hash => Ada.Strings.Hash);
Commands : Command_Map.Map;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Slots : MAT.Memory.Allocation_Map;
Iter : MAT.Memory.Allocation_Cursor;
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation) is
use type MAT.Frames.Frame_Type;
Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame);
Name : Ada.Strings.Unbounded.Unbounded_String;
Func : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr));
Ada.Text_IO.Set_Col (14);
Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size));
Ada.Text_IO.Set_Col (30);
Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread));
Ada.Text_IO.Set_Col (50);
Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time));
Ada.Text_IO.New_Line;
for I in Backtrace'Range loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Natural'Image (I));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I)));
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Backtrace (I),
Name => Name,
Func => Func,
Line => Line);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name));
if Line /= 0 then
Ada.Text_IO.Put (":");
Ada.Text_IO.Put (Util.Strings.Image (Line));
end if;
Ada.Text_IO.New_Line;
end loop;
end Print;
Filter : MAT.Expressions.Expression_Type;
begin
Filter := MAT.Expressions.Parse (Args);
Target.Memory.Find (From => MAT.Types.Target_Addr'First,
To => MAT.Types.Target_Addr'Last,
Filter => Filter,
Into => Slots);
Iter := Slots.First;
while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop
MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access);
MAT.Memory.Allocation_Maps.Next (Iter);
end loop;
exception
when E : others =>
Target.Console.Error ("Invalid selection");
end Slot_Command;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Iter : MAT.Memory.Tools.Size_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25);
Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.End_Title;
MAT.Memory.Targets.Size_Information (Memory => Target.Memory,
Sizes => Sizes);
Iter := Sizes.First;
while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter);
Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter);
Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count);
begin
Console.Start_Row;
Console.Print_Size (MAT.Consoles.F_SIZE, Size);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count);
Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total);
Console.End_Row;
end;
MAT.Memory.Tools.Size_Info_Maps.Next (Iter);
end loop;
end Sizes_Command;
-- ------------------------------
-- Threads command.
-- Collect statistics about the threads and their allocation.
-- ------------------------------
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Threads : MAT.Memory.Memory_Info_Map;
Iter : MAT.Memory.Memory_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Thread_Information (Memory => Target.Memory,
Threads => Threads);
Iter := Threads.First;
while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter);
Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter);
begin
Console.Start_Row;
Console.Print_Field (MAT.Consoles.F_THREAD, Integer (Thread));
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Memory_Info_Maps.Next (Iter);
end loop;
end Threads_Command;
-- ------------------------------
-- Frames command.
-- Collect statistics about the frames and their allocation.
-- ------------------------------
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Frames : MAT.Memory.Frame_Info_Map;
Iter : MAT.Memory.Frame_Info_Cursor;
Level : Positive := 3;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_FILE_NAME, "File", 20);
Console.Print_Title (MAT.Consoles.F_FUNCTION_NAME, "Function", 20);
Console.Print_Title (MAT.Consoles.F_LINE_NUMBER, "Line", 6);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Frame_Information (Memory => Target.Memory,
Level => Level,
Frames => Frames);
Iter := Frames.First;
while MAT.Memory.Frame_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Func : constant Types.Target_Addr := MAT.Memory.Frame_Info_Maps.Key (Iter);
Info : constant Memory.Frame_Info := MAT.Memory.Frame_Info_Maps.Element (Iter);
Name : Ada.Strings.Unbounded.Unbounded_String;
File_Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Func,
Name => Name,
Func => File_Name,
Line => Line);
Console.Start_Row;
Console.Print_Field (MAT.Consoles.F_FILE_NAME, File_Name);
Console.Print_Field (MAT.Consoles.F_FUNCTION_NAME, Name);
Console.Print_Field (MAT.Consoles.F_LINE_NUMBER, Line);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Memory.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Memory.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Memory.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Memory.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Memory.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Memory.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Frame_Info_Maps.Next (Iter);
end loop;
end Frames_Command;
-- ------------------------------
-- Symbol command.
-- Load the symbols from the binary file.
-- ------------------------------
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
MAT.Symbols.Targets.Open (Target.Symbols, Args);
exception
when Bfd.OPEN_ERROR =>
Target.Console.Error ("Cannot open symbol file '" & Args & "'");
end Symbol_Command;
-- ------------------------------
-- Exit command.
-- ------------------------------
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
raise Stop_Interp;
end Exit_Command;
-- ------------------------------
-- Open a MAT file and read the events.
-- ------------------------------
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Reader : MAT.Readers.Files.File_Reader_Type;
begin
Target.Initialize (Reader);
Reader.Open (Args);
Reader.Read_All;
exception
when E : Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot open {0}", Args);
end Open_Command;
function Get_Command (Line : in String) return String is
Pos : Natural := Util.Strings.Index (Line, ' ');
begin
if Pos <= 0 then
return Line;
else
return Line (Line'First .. Pos - 1);
end if;
end Get_Command;
-- ------------------------------
-- Execute the command given in the line.
-- ------------------------------
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String) is
Command : constant String := Get_Command (Line);
Index : constant Natural := Util.Strings.Index (Line, ' ');
Pos : constant Command_Map.Cursor := Commands.Find (Command);
begin
if Command_Map.Has_Element (Pos) then
Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last));
elsif Command'Length > 0 then
Target.Console.Error ("Command '" & Command & "' not found");
end if;
exception
when Stop_Interp =>
raise;
when E : others =>
Log.Error ("Exception: ", E);
Target.Console.Error ("Exception while processing command");
end Execute;
begin
Commands.Insert ("exit", Exit_Command'Access);
Commands.Insert ("quit", Exit_Command'Access);
Commands.Insert ("open", Open_Command'Access);
Commands.Insert ("sizes", Sizes_Command'Access);
Commands.Insert ("symbol", Symbol_Command'Access);
Commands.Insert ("slots", Slot_Command'Access);
Commands.Insert ("threads", Threads_Command'Access);
Commands.Insert ("frames", Frames_Command'Access);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-interp -- Command interpreter
-- 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.Strings;
with Util.Log.Loggers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Bfd;
with MAT.Types;
with MAT.Readers.Files;
with MAT.Memory.Tools;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Expressions;
with MAT.Frames;
with MAT.Frames.Print;
with MAT.Consoles;
package body MAT.Commands is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands");
package Command_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Command_Handler,
Equivalent_Keys => "=",
Hash => Ada.Strings.Hash);
Commands : Command_Map.Map;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Slots : MAT.Memory.Allocation_Map;
Iter : MAT.Memory.Allocation_Cursor;
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation) is
use type MAT.Frames.Frame_Type;
Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame);
Name : Ada.Strings.Unbounded.Unbounded_String;
Func : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr));
Ada.Text_IO.Set_Col (14);
Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size));
Ada.Text_IO.Set_Col (30);
Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread));
Ada.Text_IO.Set_Col (50);
Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time));
Ada.Text_IO.New_Line;
for I in Backtrace'Range loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Natural'Image (I));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I)));
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Backtrace (I),
Name => Name,
Func => Func,
Line => Line);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name));
if Line /= 0 then
Ada.Text_IO.Put (":");
Ada.Text_IO.Put (Util.Strings.Image (Line));
end if;
Ada.Text_IO.New_Line;
end loop;
end Print;
Filter : MAT.Expressions.Expression_Type;
begin
Filter := MAT.Expressions.Parse (Args);
Target.Memory.Find (From => MAT.Types.Target_Addr'First,
To => MAT.Types.Target_Addr'Last,
Filter => Filter,
Into => Slots);
Iter := Slots.First;
while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop
MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access);
MAT.Memory.Allocation_Maps.Next (Iter);
end loop;
exception
when E : others =>
Target.Console.Error ("Invalid selection");
end Slot_Command;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Iter : MAT.Memory.Tools.Size_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25);
Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.End_Title;
MAT.Memory.Targets.Size_Information (Memory => Target.Memory,
Sizes => Sizes);
Iter := Sizes.First;
while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter);
Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter);
Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count);
begin
Console.Start_Row;
Console.Print_Size (MAT.Consoles.F_SIZE, Size);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count);
Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total);
Console.End_Row;
end;
MAT.Memory.Tools.Size_Info_Maps.Next (Iter);
end loop;
end Sizes_Command;
-- ------------------------------
-- Threads command.
-- Collect statistics about the threads and their allocation.
-- ------------------------------
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Threads : MAT.Memory.Memory_Info_Map;
Iter : MAT.Memory.Memory_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Thread_Information (Memory => Target.Memory,
Threads => Threads);
Iter := Threads.First;
while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter);
Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter);
begin
Console.Start_Row;
Console.Print_Thread (MAT.Consoles.F_THREAD, Thread);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Memory_Info_Maps.Next (Iter);
end loop;
end Threads_Command;
-- ------------------------------
-- Frames command.
-- Collect statistics about the frames and their allocation.
-- ------------------------------
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Sizes : MAT.Memory.Tools.Size_Info_Map;
Frames : MAT.Memory.Frame_Info_Map;
Iter : MAT.Memory.Frame_Info_Cursor;
Level : Positive := 3;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_FILE_NAME, "File", 20);
Console.Print_Title (MAT.Consoles.F_FUNCTION_NAME, "Function", 20);
Console.Print_Title (MAT.Consoles.F_LINE_NUMBER, "Line", 6);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Frame_Information (Memory => Target.Memory,
Level => Level,
Frames => Frames);
Iter := Frames.First;
while MAT.Memory.Frame_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Func : constant Types.Target_Addr := MAT.Memory.Frame_Info_Maps.Key (Iter);
Info : constant Memory.Frame_Info := MAT.Memory.Frame_Info_Maps.Element (Iter);
Name : Ada.Strings.Unbounded.Unbounded_String;
File_Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Func,
Name => Name,
Func => File_Name,
Line => Line);
Console.Start_Row;
Console.Print_Field (MAT.Consoles.F_FILE_NAME, File_Name);
Console.Print_Field (MAT.Consoles.F_FUNCTION_NAME, Name);
Console.Print_Field (MAT.Consoles.F_LINE_NUMBER, Line);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Memory.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Memory.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Memory.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Memory.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Memory.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Memory.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Frame_Info_Maps.Next (Iter);
end loop;
end Frames_Command;
-- ------------------------------
-- Symbol command.
-- Load the symbols from the binary file.
-- ------------------------------
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
MAT.Symbols.Targets.Open (Target.Symbols, Args);
exception
when Bfd.OPEN_ERROR =>
Target.Console.Error ("Cannot open symbol file '" & Args & "'");
end Symbol_Command;
-- ------------------------------
-- Exit command.
-- ------------------------------
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
raise Stop_Interp;
end Exit_Command;
-- ------------------------------
-- Open a MAT file and read the events.
-- ------------------------------
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Reader : MAT.Readers.Files.File_Reader_Type;
begin
Target.Initialize (Reader);
Reader.Open (Args);
Reader.Read_All;
exception
when E : Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot open {0}", Args);
end Open_Command;
function Get_Command (Line : in String) return String is
Pos : Natural := Util.Strings.Index (Line, ' ');
begin
if Pos <= 0 then
return Line;
else
return Line (Line'First .. Pos - 1);
end if;
end Get_Command;
-- ------------------------------
-- Execute the command given in the line.
-- ------------------------------
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String) is
Command : constant String := Get_Command (Line);
Index : constant Natural := Util.Strings.Index (Line, ' ');
Pos : constant Command_Map.Cursor := Commands.Find (Command);
begin
if Command_Map.Has_Element (Pos) then
Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last));
elsif Command'Length > 0 then
Target.Console.Error ("Command '" & Command & "' not found");
end if;
exception
when Stop_Interp =>
raise;
when E : others =>
Log.Error ("Exception: ", E);
Target.Console.Error ("Exception while processing command");
end Execute;
begin
Commands.Insert ("exit", Exit_Command'Access);
Commands.Insert ("quit", Exit_Command'Access);
Commands.Insert ("open", Open_Command'Access);
Commands.Insert ("sizes", Sizes_Command'Access);
Commands.Insert ("symbol", Symbol_Command'Access);
Commands.Insert ("slots", Slot_Command'Access);
Commands.Insert ("threads", Threads_Command'Access);
Commands.Insert ("frames", Frames_Command'Access);
end MAT.Commands;
|
Use the Print_Thread procedure to print the thread information
|
Use the Print_Thread procedure to print the thread information
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
bab12fb075da0d7a56b62a845a64692ddc2ea32f
|
src/wiki-filters.ads
|
src/wiki-filters.ads
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
package Wiki.Filters is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.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.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Filter_Type);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
package Wiki.Filters is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.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.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Filter_Type);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
end Wiki.Filters;
|
Update the Add_Preformatted procedure
|
Update the Add_Preformatted procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a9cfbc86c85aee8871327e4d6c7043d592ad587e
|
src/orka/interface/orka-containers-bounded_vectors.ads
|
src/orka/interface/orka-containers-bounded_vectors.ads
|
-- Copyright (c) 2018 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Ada.Iterator_Interfaces;
generic
type Element_Type is private;
package Orka.Containers.Bounded_Vectors is
pragma Preelaborate;
type Cursor is private;
pragma Preelaborable_Initialization (Cursor);
No_Element : constant Cursor;
type Vector (Capacity : Positive) is tagged private
with Constant_Indexing => Element;
pragma Preelaborable_Initialization (Vector);
procedure Append (Container : in out Vector; Elements : Vector)
with Pre => Container.Length + Elements.Length <= Container.Capacity,
Post => Container.Length = Container'Old.Length + Elements.Length;
procedure Append (Container : in out Vector; Element : Element_Type)
with Pre => Container.Length < Container.Capacity,
Post => Container.Length = Container'Old.Length + 1;
-- Add the element to the end of the vector
procedure Remove_Last (Container : in out Vector; Element : out Element_Type)
with Pre => Container.Length > 0,
Post => Container.Length = Container'Old.Length - 1;
type Element_Array is array (Positive range <>) of Element_Type;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array));
procedure Update
(Container : in out Vector;
Index : Positive;
Process : not null access procedure (Element : in out Element_Type))
with Pre => Index <= Container.Length;
function Element (Container : Vector; Index : Positive) return Element_Type;
function Element
(Container : aliased Vector;
Position : Cursor) return Element_Type;
function Length (Container : Vector) return Natural
with Inline;
function Empty (Container : Vector) return Boolean
with Inline;
function Full (Container : Vector) return Boolean
with Inline;
private
function Has_Element (Position : Cursor) return Boolean is
(Position /= No_Element);
package Vector_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element);
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class;
type Vector (Capacity : Positive) is tagged record
Elements : Element_Array (1 .. Capacity) := (others => <>);
Length : Natural := 0;
end record
with Default_Iterator => Iterate,
Iterator_Element => Element_Type;
pragma Preelaborable_Initialization (Vector);
-----------------------------------------------------------------------------
type Vector_Access is access constant Vector;
type Cursor is record
Object : Vector_Access;
Index : Natural;
end record;
No_Element : constant Cursor := Cursor'(null, 0);
-----------------------------------------------------------------------------
type Iterator is limited new
Vector_Iterator_Interfaces.Reversible_Iterator with
record
Container : Vector_Access;
end record;
overriding function First (Object : Iterator) return Cursor;
overriding function Last (Object : Iterator) return Cursor;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor;
end Orka.Containers.Bounded_Vectors;
|
-- 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.
private with Ada.Iterator_Interfaces;
generic
type Element_Type is private;
package Orka.Containers.Bounded_Vectors is
pragma Preelaborate;
type Vector (Capacity : Positive) is tagged private
with Constant_Indexing => Element;
pragma Preelaborable_Initialization (Vector);
procedure Append (Container : in out Vector; Elements : Vector)
with Pre => Container.Length + Elements.Length <= Container.Capacity,
Post => Container.Length = Container'Old.Length + Elements.Length;
procedure Append (Container : in out Vector; Element : Element_Type)
with Pre => Container.Length < Container.Capacity,
Post => Container.Length = Container'Old.Length + 1;
-- Add the element to the end of the vector
procedure Remove_Last (Container : in out Vector; Element : out Element_Type)
with Pre => Container.Length > 0,
Post => Container.Length = Container'Old.Length - 1;
type Element_Array is array (Positive range <>) of Element_Type;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array));
procedure Update
(Container : in out Vector;
Index : Positive;
Process : not null access procedure (Element : in out Element_Type))
with Pre => Index <= Container.Length;
function Element (Container : Vector; Index : Positive) return Element_Type;
function Element
(Container : aliased Vector;
Position : Cursor) return Element_Type;
function Length (Container : Vector) return Natural
with Inline;
function Empty (Container : Vector) return Boolean
with Inline;
function Full (Container : Vector) return Boolean
with Inline;
private
type Vector_Access is access constant Vector;
type Cursor is record
Object : Vector_Access;
Index : Natural;
end record;
No_Element : constant Cursor := Cursor'(null, 0);
-----------------------------------------------------------------------------
function Has_Element (Position : Cursor) return Boolean is
(Position /= No_Element);
package Vector_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element);
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class;
type Vector (Capacity : Positive) is tagged record
Elements : Element_Array (1 .. Capacity) := (others => <>);
Length : Natural := 0;
end record
with Default_Iterator => Iterate,
Iterator_Element => Element_Type;
pragma Preelaborable_Initialization (Vector);
-----------------------------------------------------------------------------
type Iterator is limited new
Vector_Iterator_Interfaces.Reversible_Iterator with
record
Container : Vector_Access;
end record;
overriding function First (Object : Iterator) return Cursor;
overriding function Last (Object : Iterator) return Cursor;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor;
end Orka.Containers.Bounded_Vectors;
|
Move type Cursor to private part of package Bounded_Vectors
|
orka: Move type Cursor to private part of package Bounded_Vectors
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
0792fa33cf89864cf7e449c6919d4db2c5388aa9
|
awa/src/awa-applications-factory.ads
|
awa/src/awa-applications-factory.ads
|
-----------------------------------------------------------------------
-- awa-applications-factory -- Factory for AWA Applications
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications.Main;
with Security.Permissions;
package AWA.Applications.Factory is
-- ------------------------------
-- Application factory to setup the permission manager.
-- ------------------------------
type Application_Factory is new ASF.Applications.Main.Application_Factory with private;
-- Create the permission manager. The permission manager is created during
-- the initialization phase of the application. This implementation
-- creates a <b>AWA.Permissions.Services.Permission_Manager</b> object.
overriding
function Create_Permission_Manager (App : in Application_Factory)
return Security.Permissions.Permission_Manager_Access;
-- Set the application instance that will be used when creating the permission manager.
procedure Set_Application (Factory : in out ASF.Applications.Main.Application_Factory'Class;
App : in Application_Access);
private
type Application_Factory is new ASF.Applications.Main.Application_Factory with record
App : Application_Access := null;
end record;
end AWA.Applications.Factory;
|
-----------------------------------------------------------------------
-- awa-applications-factory -- Factory for AWA Applications
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications.Main;
with Security.Policies;
package AWA.Applications.Factory is
-- ------------------------------
-- Application factory to setup the permission manager.
-- ------------------------------
type Application_Factory is new ASF.Applications.Main.Application_Factory with private;
-- Create the security manager. The security manager is created during
-- the initialization phase of the application. This implementation
-- creates a <b>AWA.Permissions.Services.Permission_Manager</b> object.
overriding
function Create_Security_Manager (App : in Application_Factory)
return Security.Policies.Policy_Manager_Access;
-- Set the application instance that will be used when creating the permission manager.
procedure Set_Application (Factory : in out ASF.Applications.Main.Application_Factory'Class;
App : in Application_Access);
private
type Application_Factory is new ASF.Applications.Main.Application_Factory with record
App : Application_Access := null;
end record;
end AWA.Applications.Factory;
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7381bb852475d8fc710c1984955d948fd32ab3a7
|
mat/src/mat-expressions.adb
|
mat/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Memory;
package body MAT.Expressions is
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Ada.Strings.Unbounded.To_Unbounded_String (Name),
Inside => Kind);
return Result;
end Create_Inside;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Memory;
package body MAT.Expressions is
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Ada.Strings.Unbounded.To_Unbounded_String (Name),
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
end MAT.Expressions;
|
Implement the Create_Size operation
|
Implement the Create_Size operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a568974d9a8ff1e480cbe34c32b5119ff9d6b40c
|
mat/src/mat-readers-streams-sockets.adb
|
mat/src/mat-readers-streams-sockets.adb
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- 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.Streams;
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Readers.Streams.Sockets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets");
BUFFER_SIZE : constant Natural := 100 * 1024;
MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048;
-- ------------------------------
-- Initialize the socket listener.
-- ------------------------------
overriding
procedure Initialize (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Create_Selector (Listener.Accept_Selector);
end Initialize;
-- ------------------------------
-- Open the socket to accept connections and start the listener task.
-- ------------------------------
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Starting the listener socket task");
Listener.Listener.Start (Address);
end Start;
-- ------------------------------
-- Stop the listener socket.
-- ------------------------------
procedure Stop (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Abort_Selector (Listener.Accept_Selector);
end Stop;
task body Socket_Listener_Task is
use type GNAT.Sockets.Socket_Type;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := S;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
while not Instance.Stop loop
GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status);
if Socket /= GNAT.Sockets.No_Socket then
Instance.Socket.Open (Socket);
Instance.Read_All;
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
end Socket_Listener_Task;
task body Socket_Reader_Task is
use type GNAT.Sockets.Socket_Type;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := S;
-- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1);
-- Address.Addr := GNAT.Sockets.Any_Inet_Addr;
-- Address.Port := 4096;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
-- Address := GNAT.Sockets.Get_Socket_Name (Server);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
while not Instance.Stop loop
GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status);
if Socket /= GNAT.Sockets.No_Socket then
Instance.Socket.Open (Socket);
Instance.Read_All;
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
exception
when E : others =>
Log.Error ("Exception", E);
end Socket_Reader_Task;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Reading server stream");
Reader.Stream.Initialize (Size => BUFFER_SIZE,
Input => Reader.Socket'Unchecked_Access,
Output => null);
Reader.Server.Start (Reader'Unchecked_Access, Address);
end Open;
procedure Close (Reader : in out Socket_Reader_Type) is
begin
Reader.Stop := True;
end Close;
end MAT.Readers.Streams.Sockets;
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- 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.Streams;
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Readers.Streams.Sockets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets");
BUFFER_SIZE : constant Natural := 100 * 1024;
MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048;
-- ------------------------------
-- Initialize the socket listener.
-- ------------------------------
overriding
procedure Initialize (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Create_Selector (Listener.Accept_Selector);
end Initialize;
-- ------------------------------
-- Destroy the socket listener.
-- ------------------------------
overriding
procedure Finalize (Listener : in out Socket_Listener_Type) is
use type GNAT.Sockets.Selector_Type;
begin
GNAT.Sockets.Close_Selector (Listener.Accept_Selector);
end Finalize;
-- ------------------------------
-- Open the socket to accept connections and start the listener task.
-- ------------------------------
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Starting the listener socket task");
Listener.Listener.Start (Address);
end Start;
-- ------------------------------
-- Stop the listener socket.
-- ------------------------------
procedure Stop (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Abort_Selector (Listener.Accept_Selector);
end Stop;
task body Socket_Listener_Task is
use type GNAT.Sockets.Socket_Type;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := S;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
while not Instance.Stop loop
GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status);
if Socket /= GNAT.Sockets.No_Socket then
Instance.Socket.Open (Socket);
Instance.Read_All;
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
end Socket_Listener_Task;
task body Socket_Reader_Task is
use type GNAT.Sockets.Socket_Type;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := S;
-- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1);
-- Address.Addr := GNAT.Sockets.Any_Inet_Addr;
-- Address.Port := 4096;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
-- Address := GNAT.Sockets.Get_Socket_Name (Server);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
while not Instance.Stop loop
GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status);
if Socket /= GNAT.Sockets.No_Socket then
Instance.Socket.Open (Socket);
Instance.Read_All;
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
exception
when E : others =>
Log.Error ("Exception", E);
end Socket_Reader_Task;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Reading server stream");
Reader.Stream.Initialize (Size => BUFFER_SIZE,
Input => Reader.Socket'Unchecked_Access,
Output => null);
Reader.Server.Start (Reader'Unchecked_Access, Address);
end Open;
procedure Close (Reader : in out Socket_Reader_Type) is
begin
Reader.Stop := True;
end Close;
end MAT.Readers.Streams.Sockets;
|
Implement the Finalize procedure
|
Implement the Finalize procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.