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
12ad158dfb91ce68e8962f6e8d44633207964f0d
regtests/el-utils-tests.adb
regtests/el-utils-tests.adb
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Utils.Tests is use Util.Tests; use Util.Beans.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Utils.Expand", Test_Expand_Properties'Access); Caller.Add_Test (Suite, "Test EL.Utils.Expand (recursion)", Test_Expand_Recursion'Access); Caller.Add_Test (Suite, "Test EL.Utils.Eval", Test_Eval'Access); end Add_Tests; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Properties (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("unknown", "#{not_defined}"); Props.Set ("user", "joe"); Props.Set ("home", "/home"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/home/joe", String '(Result.Get ("homedir")), "Invalid expansion"); Assert_Equals (T, "/home/joe/context", String '(Result.Get ("context")), "Invalid expansion"); Assert_Equals (T, "", String '(Result.Get ("unknown")), "Invalid expansion"); end Test_Expand_Properties; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Recursion (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("user", "joe"); Props.Set ("home", "#{context}"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/joe/context/joe/context/joe/context/joe", String '(Result.Get ("homedir")), "Invalid expansion"); end Test_Expand_Recursion; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Eval (T : in out Test) is Context : EL.Contexts.Default.Default_Context; begin Assert_Equals (T, "1", EL.Utils.Eval (Value => "1", Context => Context), "Invalid eval <empty string>"); Assert_Equals (T, "3", EL.Utils.Eval (Value => "#{2+1}", Context => Context), "Invalid eval <valid expr>"); declare Value, Result : Util.Beans.Objects.Object; begin Value := Util.Beans.Objects.To_Object (Integer '(123)); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); Value := Util.Beans.Objects.To_Object (String '("345")); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); end; end Test_Eval; end EL.Utils.Tests;
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Utils.Tests is use Util.Tests; use Util.Beans.Objects; package Caller is new Util.Test_Caller (Test, "EL.Utils"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Utils.Expand", Test_Expand_Properties'Access); Caller.Add_Test (Suite, "Test EL.Utils.Expand (recursion)", Test_Expand_Recursion'Access); Caller.Add_Test (Suite, "Test EL.Utils.Eval", Test_Eval'Access); end Add_Tests; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Properties (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("unknown", "#{not_defined}"); Props.Set ("user", "joe"); Props.Set ("home", "/home"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/home/joe", String '(Result.Get ("homedir")), "Invalid expansion"); Assert_Equals (T, "/home/joe/context", String '(Result.Get ("context")), "Invalid expansion"); Assert_Equals (T, "", String '(Result.Get ("unknown")), "Invalid expansion"); end Test_Expand_Properties; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Recursion (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("user", "joe"); Props.Set ("home", "#{context}"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/joe/context/joe/context/joe/context/joe", String '(Result.Get ("homedir")), "Invalid expansion"); end Test_Expand_Recursion; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Eval (T : in out Test) is Context : EL.Contexts.Default.Default_Context; begin Assert_Equals (T, "1", EL.Utils.Eval (Value => "1", Context => Context), "Invalid eval <empty string>"); Assert_Equals (T, "3", EL.Utils.Eval (Value => "#{2+1}", Context => Context), "Invalid eval <valid expr>"); declare Value, Result : Util.Beans.Objects.Object; begin Value := Util.Beans.Objects.To_Object (Integer '(123)); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); Value := Util.Beans.Objects.To_Object (String '("345")); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); end; end Test_Eval; end EL.Utils.Tests;
Use the name EL.Utils for the test
Use the name EL.Utils for the test
Ada
apache-2.0
stcarrez/ada-el
5547fc611ba0d02028b47fccbcf9f78fdd19da52
src/wiki-render-text.ads
src/wiki-render-text.ads
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams; -- == Text Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Text_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Text_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Text_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Text_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Text_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); overriding procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Text_Renderer); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams; -- == Text Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. procedure Add_Header (Document : in out Text_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Text_Renderer); -- 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 Text_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Text_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Text_Renderer); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
Update the Text_Renderer to drop several non-overriding operations
Update the Text_Renderer to drop several non-overriding operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
df91ecc0676b2a1ae9b6dd9667a25de37824c2d2
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Wiki.Nodes.Add_Blockquote (Document, Level); end if; 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. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Wiki.Nodes.Add_List_Item (Document, Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, To_Wide_Wide_String (Format)); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Wiki.Nodes.Add_Blockquote (Document, Level); end if; 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. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Wiki.Nodes.Add_List_Item (Document, Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, To_Wide_Wide_String (Format)); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; end Wiki.Filters;
Implement the Add_Filter procedure
Implement the Add_Filter procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a716eb706d9eda1a17745c21af8aebc014d88b95
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
08ca7bec73e1deb99d4807e9fee10f94cbb7e447
boards/HiFive1/src/hifive1.ads
boards/HiFive1/src/hifive1.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.Device; use FE310.Device; with FE310.GPIO; use FE310.GPIO; package HiFive1 is HF1_Pin_0 : GPIO_Point renames P16; HF1_Pin_1 : GPIO_Point renames P17; HF1_Pin_2 : GPIO_Point renames P18; HF1_Pin_3 : GPIO_Point renames P19; -- Green LED HF1_Pin_4 : GPIO_Point renames P20; HF1_Pin_5 : GPIO_Point renames P21; -- Blue LED HF1_Pin_6 : GPIO_Point renames P22; -- Red LED HF1_Pin_7 : GPIO_Point renames P23; HF1_Pin_8 : GPIO_Point renames P00; HF1_Pin_9 : GPIO_Point renames P01; HF1_Pin_10 : GPIO_Point renames P02; HF1_Pin_11 : GPIO_Point renames P03; HF1_Pin_12 : GPIO_Point renames P04; HF1_Pin_13 : GPIO_Point renames P05; -- HF1_Pin_14 is not connected HF1_Pin_15 : GPIO_Point renames P09; HF1_Pin_16 : GPIO_Point renames P10; HF1_Pin_17 : GPIO_Point renames P11; HF1_Pin_18 : GPIO_Point renames P12; HF1_Pin_19 : GPIO_Point renames P13; end HiFive1;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.Device; use FE310.Device; with FE310.GPIO; use FE310.GPIO; package HiFive1 is HF1_Pin_0 : GPIO_Point renames P16; -- IOF 0: UART 0 RX HF1_Pin_1 : GPIO_Point renames P17; -- IOF 0: UART 0 TX HF1_Pin_2 : GPIO_Point renames P18; HF1_Pin_3 : GPIO_Point renames P19; -- | IOF 1 : PWM 1 HF1_Pin_4 : GPIO_Point renames P20; -- | IOF 1 : PWM 1 HF1_Pin_5 : GPIO_Point renames P21; -- | IOF 1 : PWM 1 HF1_Pin_6 : GPIO_Point renames P22; -- | IOF 1 : PWM 1 HF1_Pin_7 : GPIO_Point renames P23; HF1_Pin_8 : GPIO_Point renames P00; -- | IOF 1 : PWM 0 HF1_Pin_9 : GPIO_Point renames P01; -- | IOF 1 : PWM 0 HF1_Pin_10 : GPIO_Point renames P02; -- | IOF 1 : PWM 0 HF1_Pin_11 : GPIO_Point renames P03; -- IOF 0: SPI 1 MOSI | IOF 1 : PWM 0 HF1_Pin_12 : GPIO_Point renames P04; -- IOF 0: SPI 1 MISO HF1_Pin_13 : GPIO_Point renames P05; -- IOF 0: SPI 1 SCK -- HF1_Pin_14 is not connected HF1_Pin_15 : GPIO_Point renames P09; HF1_Pin_16 : GPIO_Point renames P10; -- | IOF 1 : PWM 2 HF1_Pin_17 : GPIO_Point renames P11; -- | IOF 1 : PWM 2 HF1_Pin_18 : GPIO_Point renames P12; -- | IOF 1 : PWM 2 HF1_Pin_19 : GPIO_Point renames P13; -- | IOF 1 : PWM 2 end HiFive1;
Add comments on the IO function of the pins
HiFive1: Add comments on the IO function of the pins
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
91a27be3728b22246aa080de0024eeaa9307db40
awa/src/awa-commands.ads
awa/src/awa-commands.ads
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; with ASF.Applications.Main; with Ada.Exceptions; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; -- == AWA Commands == -- The `AWA.Commands` package provides a simple framework with commands that -- allow to start, stop, configure and manage the web application. It is also -- possible to provide your own commands. The command framework handles the -- parsing of command line options, identification of the command to execute -- and execution of the selected command. -- -- @include-doc docs/command.md -- -- === Integration === -- The `AWA.Commands` framework is split in several generic packages that -- must be instantiated. The `AWA.Commands.Drivers` generic package is -- the primary package that must be instantiated. It provides the core -- command line driver framework on top of which the commands are implemented. -- The instantiation needs two parameter: the name of the application and -- the type of the web server container. When using Ada Web Server, the -- following instantiation example can be used: -- -- with Servlet.Server.Web; -- with AWA.Commands.Drivers; -- ... -- package Server_Commands is -- new AWA.Commands.Drivers -- (Driver_Name => "atlas", -- Container_Type => Servlet.Server.Web.AWS_Container); -- -- The `Driver_Name` is used to print the name of the command when -- some usage or help is printed. The `Container_Type` is used to -- declare the web container onto which applications are registered -- and which provides the web server core implementation. The web -- server container instance is available through the `WS` variable -- defined in the `Server_Commands` package. -- -- Once the command driver is instantiated, it is necessary to instantiate -- each command that you wish to integrate in the final application. -- For example, to integrate the `start` command, you will do: -- -- with AWA.Commands.Start; -- ... -- package Start_Command is new AWA.Commands.Start (Server_Commands); -- -- To integrate the `stop` command, you will do: -- -- with AWA.Commands.Stop; -- ... -- package Stop_Command is new AWA.Commands.Stop (Server_Commands); -- -- The instantiation of one of the command, automatically registers the -- command to the command driver. -- package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging -- it with the keystore file if there is one. procedure Configure (Application : in out ASF.Applications.Main.Application'Class; Name : in String; Context : in out Context_Type); procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence); -- Configure the logs. procedure Configure_Logs (Root : in String; Debug : in Boolean; Dump : in Boolean; Verbose : in Boolean); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type; Path : in String); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; with ASF.Applications.Main; with Ada.Exceptions; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; -- == AWA Commands == -- The `AWA.Commands` package provides a simple framework with commands that -- allow to start, stop, configure and manage the web application. It is also -- possible to provide your own commands. The command framework handles the -- parsing of command line options, identification of the command to execute -- and execution of the selected command. -- -- @include-doc docs/command.md -- -- === Integration === -- The `AWA.Commands` framework is split in several generic packages that -- must be instantiated. The `AWA.Commands.Drivers` generic package is -- the primary package that must be instantiated. It provides the core -- command line driver framework on top of which the commands are implemented. -- The instantiation needs two parameter: the name of the application and -- the type of the web server container. When using Ada Web Server, the -- following instantiation example can be used: -- -- with Servlet.Server.Web; -- with AWA.Commands.Drivers; -- ... -- package Server_Commands is -- new AWA.Commands.Drivers -- (Driver_Name => "atlas", -- Container_Type => Servlet.Server.Web.AWS_Container); -- -- The `Driver_Name` is used to print the name of the command when -- some usage or help is printed. The `Container_Type` is used to -- declare the web container onto which applications are registered -- and which provides the web server core implementation. The web -- server container instance is available through the `WS` variable -- defined in the `Server_Commands` package. -- -- Once the command driver is instantiated, it is necessary to instantiate -- each command that you wish to integrate in the final application. -- For example, to integrate the `start` command, you will do: -- -- with AWA.Commands.Start; -- ... -- package Start_Command is new AWA.Commands.Start (Server_Commands); -- -- To integrate the `stop` command, you will do: -- -- with AWA.Commands.Stop; -- ... -- package Stop_Command is new AWA.Commands.Stop (Server_Commands); -- -- The instantiation of one of the command, automatically registers the -- command to the command driver. -- package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging -- it with the keystore file if there is one. procedure Configure (Application : in out ASF.Applications.Main.Application'Class; Name : in String; Context : in out Context_Type); procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence); -- Configure the logs. procedure Configure_Logs (Root : in String; Debug : in Boolean; Dump : in Boolean; Verbose : in Boolean); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type; Path : in String); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Keystore_Opened : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
Add Keystore_Opened boolean and remove unused Data_Path record members
Add Keystore_Opened boolean and remove unused Data_Path record members
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
41acee3f592cf6d056ec7cd194890718211f90a5
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
Letractively/ada-security
08e2589677f1ba5f8d53b5df7422cba470cb8f87
matp/src/mat-commands.ads
matp/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is Stop_Interp : exception; -- Exception raised by a command when a filter expression is invalid. Filter_Error : exception; -- Exception raised by a command when some command argument is invalid. Usage_Error : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- 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); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Timeline command. -- Identify the interesting timeline groups in the events and display them. procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Addr command to print a description of an address. procedure Addr_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is -- Exception raised to stop the program. Stop_Interp : exception; -- Exception raised to stop the command (program continues). Stop_Command : exception; -- Exception raised by a command when a filter expression is invalid. Filter_Error : exception; -- Exception raised by a command when some command argument is invalid. Usage_Error : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- 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); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Timeline command. -- Identify the interesting timeline groups in the events and display them. procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Addr command to print a description of an address. procedure Addr_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Declare the Stop_Command exception
Declare the Stop_Command exception
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
938da95dd7e21539606c956da967897280fa46f5
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; with ADO.Configs; package body ADO.Queries.Loaders is use Util.Log; use ADO.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Connections.Driver_Access := Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Connections.Configuration'Class) is Paths : constant String := Config.Get_Property (Configs.QUERY_PATHS_CONFIG); Load : constant Boolean := Config.Get_Property (Configs.QUERY_LOAD_CONFIG) = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := 0; Manager.Files (File.File).Next_Check := 0; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; with ADO.Configs; package body ADO.Queries.Loaders is use Util.Log; use ADO.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Connections.Driver_Access := Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Connections.Configuration'Class) is function Get_Config (Name : in String) return String; function Get_Config (Name : in String) return String is Value : constant String := Config.Get_Property (Name); begin if Value'Length > 0 then return Value; else return Ado.Configs.Get_Config (Name); end if; end Get_Config; Paths : constant String := Get_Config (Configs.QUERY_PATHS_CONFIG); Load : constant Boolean := Get_Config (Configs.QUERY_LOAD_CONFIG) = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := 0; Manager.Files (File.File).Next_Check := 0; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Fix Initialize to look at the global configuration when a configuration parameter is not found
Fix Initialize to look at the global configuration when a configuration parameter is not found
Ada
apache-2.0
stcarrez/ada-ado
9e9f4d0cd1c6b512f263c0201b587809fca41cc4
regtests/util-streams-buffered-lzma-tests.ads
regtests/util-streams-buffered-lzma-tests.ads
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered streams -- Copyright (C) 2018, 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.Tests; package Util.Streams.Buffered.Lzma.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Compress_Stream (T : in out Test); procedure Test_Compress_File_Stream (T : in out Test); procedure Test_Compress_Decompress_Stream (T : in out Test); end Util.Streams.Buffered.Lzma.Tests;
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered streams -- Copyright (C) 2018, 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.Tests; package Util.Streams.Buffered.Lzma.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Compress_Stream (T : in out Test); procedure Test_Compress_File_Stream (T : in out Test); procedure Test_Compress_Decompress_Stream (T : in out Test); procedure Test_Compress_Encrypt_Decompress_Decrypt_Stream (T : in out Test); end Util.Streams.Buffered.Lzma.Tests;
Declare Test_Compress_Encrypt_Decompress_Decrypt_Stream
Declare Test_Compress_Encrypt_Decompress_Decrypt_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
58d971135e8295f0a9e5920503e71ba8d31a130e
samples/openid.adb
samples/openid.adb
----------------------------------------------------------------------- -- openid -- Example of OpenID 2.0 Authentication -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Applications; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with Util.Beans.Objects; with Util.Log.Loggers; with Users; with AWS.Net.SSL; with Security.Openid; with Security.Openid.Servlets; procedure Openid is use ASF.Applications; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); CONTEXT_PATH : constant String := "/openid"; CONFIG_PATH : constant String := "samples.properties"; App : aliased ASF.Applications.Main.Application; Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased Security.Openid.Servlets.Verify_Auth_Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Register ("samplesMsg", "samples"); App.Set_Global ("contextPath", "/openid"); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "openid"); App.Set_Global ("version", "0.1"); App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC)); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); -- Register the filters App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); -- Install the debug filter. App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html"); WS.Start; delay 600.0; App.Close; exception when E : others => Ada.Text_IO.Put_Line ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Openid;
----------------------------------------------------------------------- -- openid -- Example of OpenID 2.0 Authentication -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Applications; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with Util.Beans.Objects; with Util.Log.Loggers; with Users; with AWS.Net.SSL; with ASF.Security.Servlets; procedure Openid is use ASF.Applications; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); CONTEXT_PATH : constant String := "/openid"; CONFIG_PATH : constant String := "samples.properties"; App : aliased ASF.Applications.Main.Application; Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Register ("samplesMsg", "samples"); App.Set_Global ("contextPath", "/openid"); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "openid"); App.Set_Global ("version", "0.1"); App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC)); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); -- Register the filters App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); -- Install the debug filter. App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html"); WS.Start; delay 600.0; App.Close; exception when E : others => Ada.Text_IO.Put_Line ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Openid;
Fix compilation after Ada Security integration
Fix compilation after Ada Security integration
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
7e7fbc6900c2e3b55149205d56ca32511e2d0144
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.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); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_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; 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 (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_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 Ada.Containers.Doubly_Linked_Lists; 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); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_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; 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 (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_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; package Socket_Client_Lists is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Socket_Reader_Type_Access); type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; Clients : Socket_Client_Lists.List; end record; end MAT.Readers.Streams.Sockets;
Declare the Socket_Client_Lists package and add a list of clients in the Socket_Listener_Type
Declare the Socket_Client_Lists package and add a list of clients in the Socket_Listener_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
823c16780d7e326deb6b505acd5ed9eb5682f76f
src/gen.ads
src/gen.ads
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 313; end Gen;
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 339; end Gen;
Update the revision
Update the revision
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
91763e1a67f1a1a9d82ec9a0068d41d7c090b566
orka_transforms/src/orka-transforms-simd_vectors.ads
orka_transforms/src/orka-transforms-simd_vectors.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics; generic type Element_Type is digits <>; type Vector_Type is array (Index_4D) of Element_Type; with function Multiply_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Minus_Vector (Elements : Vector_Type) return Vector_Type; with function Absolute_Vector (Elements : Vector_Type) return Vector_Type; with function Sum (Elements : Vector_Type) return Element_Type; with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type; with function Reciprocal_Sqrt (Elements : Vector_Type) return Vector_Type; with function Cross_Product (Left, Right : Vector_Type) return Vector_Type; with function Is_Equal_Vectors (Left, Right : Vector_Type) return Boolean; package Orka.Transforms.SIMD_Vectors is pragma Pure; subtype Vector4 is Vector_Type; type Direction is new Vector4 with Dynamic_Predicate => Vector4 (Direction) (W) = 0.0 or else raise Constraint_Error with "Vector is not a direction (w /= 0.0)"; type Point is new Vector4 with Dynamic_Predicate => Vector4 (Point) (W) = 1.0 or else raise Constraint_Error with "Vector is not a point (w /= 1.0)"; Zero_Vector : constant Vector4 := (0.0, 0.0, 0.0, 0.0); Zero_Direction : constant Direction := (0.0, 0.0, 0.0, 0.0); Zero_Point : constant Point := (0.0, 0.0, 0.0, 1.0); function To_Radians (Angle : Element_Type) return Element_Type is (Angle / 180.0 * Ada.Numerics.Pi); function To_Degrees (Angle : Element_Type) return Element_Type is (Angle / Ada.Numerics.Pi * 180.0); function "=" (Left, Right : Vector_Type) return Boolean renames Is_Equal_Vectors; function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors; function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors; function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector; function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector; function "*" (Left, Right : Vector_Type) return Vector_Type renames Multiply_Vectors; function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type; ---------------------------------------------------------------------------- function "*" (Factor : Element_Type; Elements : Direction) return Direction; function "*" (Elements : Direction; Factor : Element_Type) return Direction; function "-" (Elements : Point) return Point; function "-" (Left, Right : Direction) return Direction; function "+" (Left, Right : Direction) return Direction; function "+" (Left : Point; Right : Direction) return Point; function "+" (Left : Direction; Right : Point) return Point; function "-" (Left, Right : Point) return Direction; ---------------------------------------------------------------------------- function Magnitude2 (Elements : Vector_Type) return Element_Type with Inline; function Magnitude (Elements : Vector_Type) return Element_Type; -- Return the magnitude or length of the vector function Length (Elements : Vector_Type) return Element_Type renames Magnitude; -- Return the magnitude or length of the vector function Normalize (Elements : Vector_Type) return Vector_Type; -- Return the unit vector of the given vector function Normalize_Fast (Elements : Vector_Type) return Vector_Type; -- Return the unit vector of the given vector -- -- This function may be faster than Normalize, but less accurate. function Normalized (Elements : Vector_Type) return Boolean; -- Return True if the vector is normalized, False otherwise function Distance (Left, Right : Point) return Element_Type; -- Return the distance between two points function Projection (Elements, Direction : Vector_Type) return Vector_Type; -- Return the projection of a vector in some direction function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type; -- Return a vector perpendicular to the projection of the vector in -- the given direction function Angle (Left, Right : Vector_Type) return Element_Type; -- Return the angle in radians between two vectors function Dot (Left, Right : Vector_Type) return Element_Type; function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product; function Slerp (Left, Right : Vector_Type; Weight : Element_Type) return Vector_Type with Pre => Weight in 0.0 .. 1.0, Post => Normalized (Slerp'Result); -- Return the interpolated unit vector on the shortest arc -- between the Left and Right vectors end Orka.Transforms.SIMD_Vectors;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics; generic type Element_Type is digits <>; type Vector_Type is array (Index_4D) of Element_Type; with function Multiply_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Minus_Vector (Elements : Vector_Type) return Vector_Type; with function Absolute_Vector (Elements : Vector_Type) return Vector_Type; with function Sum (Elements : Vector_Type) return Element_Type; with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type; with function Reciprocal_Sqrt (Elements : Vector_Type) return Vector_Type; with function Cross_Product (Left, Right : Vector_Type) return Vector_Type; with function Is_Equal_Vectors (Left, Right : Vector_Type) return Boolean; package Orka.Transforms.SIMD_Vectors is pragma Pure; subtype Vector4 is Vector_Type; type Direction is new Vector4 with Dynamic_Predicate => Vector4 (Direction) (W) = 0.0 or else raise Constraint_Error with "Vector is not a direction (w /= 0.0)"; type Point is new Vector4 with Dynamic_Predicate => Vector4 (Point) (W) = 1.0 or else raise Constraint_Error with "Vector is not a point (w /= 1.0)"; Zero_Vector : constant Vector4 := (0.0, 0.0, 0.0, 0.0); Zero_Direction : constant Direction := (0.0, 0.0, 0.0, 0.0); Zero_Point : constant Point := (0.0, 0.0, 0.0, 1.0); function To_Radians (Angle : Element_Type) return Element_Type is (Angle / 180.0 * Ada.Numerics.Pi); function To_Degrees (Angle : Element_Type) return Element_Type is (Angle / Ada.Numerics.Pi * 180.0); function "=" (Left, Right : Vector_Type) return Boolean renames Is_Equal_Vectors; function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors; function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors; function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector; function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector; function "*" (Left, Right : Vector_Type) return Vector_Type renames Multiply_Vectors; function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type; ---------------------------------------------------------------------------- function "*" (Factor : Element_Type; Elements : Direction) return Direction; function "*" (Elements : Direction; Factor : Element_Type) return Direction; function "-" (Elements : Point) return Point; function "-" (Left, Right : Direction) return Direction; function "+" (Left, Right : Direction) return Direction; function "+" (Left : Point; Right : Direction) return Point; function "+" (Left : Direction; Right : Point) return Point; function "-" (Left, Right : Point) return Direction; ---------------------------------------------------------------------------- function Magnitude2 (Elements : Vector_Type) return Element_Type with Inline; function Magnitude (Elements : Vector_Type) return Element_Type; -- Return the magnitude or length of the vector function Norm (Elements : Vector_Type) return Element_Type renames Magnitude; -- Return the magnitude or length of the vector function Normalize (Elements : Vector_Type) return Vector_Type; -- Return the unit vector of the given vector function Normalize_Fast (Elements : Vector_Type) return Vector_Type; -- Return the unit vector of the given vector -- -- This function may be faster than Normalize, but less accurate. function Normalized (Elements : Vector_Type) return Boolean; -- Return True if the vector is normalized, False otherwise function Distance (Left, Right : Point) return Element_Type; -- Return the distance between two points function Projection (Elements, Direction : Vector_Type) return Vector_Type; -- Return the projection of a vector in some direction function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type; -- Return a vector perpendicular to the projection of the vector in -- the given direction function Angle (Left, Right : Vector_Type) return Element_Type; -- Return the angle in radians between two vectors function Dot (Left, Right : Vector_Type) return Element_Type; function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product; function Slerp (Left, Right : Vector_Type; Weight : Element_Type) return Vector_Type with Pre => Weight in 0.0 .. 1.0, Post => Normalized (Slerp'Result); -- Return the interpolated unit vector on the shortest arc -- between the Left and Right vectors end Orka.Transforms.SIMD_Vectors;
Rename function Length to Norm in package SIMD_Vectors
transforms: Rename function Length to Norm in package SIMD_Vectors Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
4089d3b09b8d475db866c55c73c4187e7fd5f244
awa/plugins/awa-storages/src/awa-storages-servlets.adb
awa/plugins/awa-storages/src/awa-storages-servlets.adb
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Util.Log.Loggers; with Util.Strings; with ADO.Objects; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is URI : constant String := Request.Get_Path_Info; pragma Unreferenced (Server); Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; Pos : Natural; begin if URI'Length <= 1 or else URI (URI'First) /= '/' then Log.Info ("Invalid storage URI: {0}", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; -- Extract the storage identifier from the URI. Pos := Util.Strings.Index (URI, '/', URI'First + 1); if Pos = 0 then Pos := URI'Last; else Pos := Pos - 1; end if; Id := ADO.Identifier'Value (URI (URI'First + 1 .. Pos)); Log.Info ("GET storage file {0}", URI); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("Storage file {0} not found", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; end AWA.Storages.Servlets;
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with ADO.Objects; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data); if Data.Is_Null then Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server); Store : constant String := Request.Get_Path_Parameter (1); Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; begin if Store'Length = 0 then Log.Info ("Invalid storage URI: {0}", Store); return; end if; -- Extract the storage identifier from the URI. Id := ADO.Identifier'Value (Store); Log.Info ("GET storage file {0}", Store); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); end Load; end AWA.Storages.Servlets;
Implement the Load procedure to load the storage file data Use the Load procedure to get the file data and return it (the Load procedure can be overriden in some inherited type)
Implement the Load procedure to load the storage file data Use the Load procedure to get the file data and return it (the Load procedure can be overriden in some inherited type)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
38b1f93dbf232debc8a53409aada0245f7cf7632
src/bbox-api.adb
src/bbox-api.adb
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Response.Get_Body); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; end Bbox.API;
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Response.Get_Body); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; -- ------------------------------ -- Execute a PUT operation on the Bbox API to change some parameter. -- ------------------------------ procedure Put (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Put {0}", URI); Client.Http.Put (URI, Params, Response); end Put; end Bbox.API;
Implement the Put procedure on the Bbox API
Implement the Put procedure on the Bbox API
Ada
apache-2.0
stcarrez/bbox-ada-api
1e2fa9d1a6739cdb6ace2434088e3e172e77f2c7
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; package body Util.Properties.Bundles is use Util.Log; Log : constant Loggers.Logger := 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); 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; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; 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; Bundle.Impl.Count := Bundle.Impl.Count + 1; 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; Path : constant String := To_String (Factory.Path); Filter : constant Filter_Type := (Ordinary_File => True, others => False); Pattern : constant String := Name & "*.properties"; Ent : Directory_Entry_Type; Names : Util.Strings.String_Set.Set; Search : Search_Type; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Start_Search (Search, Directory => Path, Pattern => Pattern, Filter => Filter); Factory.Lock.Write; begin -- Scan the directory and load all the property files. while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); Bundle : constant Bundle_Manager_Access := new Manager; Bundle_Name : constant Name_Access := new String '(Simple (Simple'First .. Simple'Last - 11)); begin Log.Debug ("Loading file {0}", File_Path); Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Found := True; Names.Insert (Bundle_Name); end; end loop; -- 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; -- ------------------------------ -- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; with Util.Strings.Maps; package body Util.Properties.Bundles is use Util.Log; Log : constant Loggers.Logger := 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); 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; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; 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; Bundle.Impl.Count := Bundle.Impl.Count + 1; 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; Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; Files : Util.Strings.Maps.Map; Iter : Util.Strings.Maps.Cursor; procedure Process_File (Name : in String; File_Path : in String) is Bundle : constant Bundle_Manager_Access := new Manager; Bundle_Name : constant Name_Access := new String '(Name (Name'First .. Name'Last - 11)); begin Log.Debug ("Loading file {0}", File_Path); Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Found := True; Names.Insert (Bundle_Name); end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Util.Files.Find_Files_Path (Pattern => Pattern, Path => Path, Into => Files); Factory.Lock.Write; begin Iter := Files.First; while Util.Strings.Maps.Has_Element (Iter) loop Util.Strings.Maps.Query_Element (Iter, Process_File'Access); Util.Strings.Maps.Next (Iter); end loop; -- 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; -- ------------------------------ -- 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;
Use Find_Files_Path to search the resource bundles in several directories
Use Find_Files_Path to search the resource bundles in several directories
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
e7b381463d9cb0282e210c23309726929e044d9c
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; with Wiki.Render.Links; -- == HTML Renderer == -- The <tt>Html_Renderer</tt> allows to render a wiki document into an HTML content. -- package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Wiki.Render.Links.Link_Renderer_Access); -- Set the render TOC flag that controls the TOC rendering. procedure Set_Render_TOC (Engine : in out Html_Renderer; State : in Boolean); -- Set the no-newline mode to avoid emitting newlines (disabled by default). procedure Set_No_Newline (Engine : in out Html_Renderer; Enable : in Boolean); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Get the current section number. function Get_Section_Number (Engine : in Html_Renderer; Prefix : in Wiki.Strings.WString; Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString; -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Html_Renderer; Level : in Natural); -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type Toc_Number_Array is array (1 .. 6) of Natural; type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Enable_Render_TOC : Boolean := False; TOC_Rendered : Boolean := False; No_Newline : Boolean := False; Current_Level : Natural := 0; Html_Tag : Wiki.Html_Tag := BODY_TAG; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; Current_Section : Toc_Number_Array := (others => 0); Section_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Render the table of content. procedure Render_TOC (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Level : in Natural); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Returns true if the HTML element being included is already contained in a paragraph. -- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup. function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; with Wiki.Render.Links; -- == HTML Renderer == -- The <tt>Html_Renderer</tt> allows to render a wiki document into an HTML content. -- package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Wiki.Render.Links.Link_Renderer_Access); -- Set the render TOC flag that controls the TOC rendering. procedure Set_Render_TOC (Engine : in out Html_Renderer; State : in Boolean); -- Set the no-newline mode to avoid emitting newlines (disabled by default). procedure Set_No_Newline (Engine : in out Html_Renderer; Enable : in Boolean); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Get the current section number. function Get_Section_Number (Engine : in Html_Renderer; Prefix : in Wiki.Strings.WString; Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString; -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Html_Renderer; Level : in Natural); -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Render a table component such as N_TABLE, N_ROW or N_COLUMN. procedure Render_Table (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type; Tag : in String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type Toc_Number_Array is array (1 .. 6) of Natural; type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Enable_Render_TOC : Boolean := False; TOC_Rendered : Boolean := False; No_Newline : Boolean := False; Current_Level : Natural := 0; Html_Tag : Wiki.Html_Tag := BODY_TAG; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; Current_Section : Toc_Number_Array := (others => 0); Section_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Render the table of content. procedure Render_TOC (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Level : in Natural); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Returns true if the HTML element being included is already contained in a paragraph. -- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup. function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean; end Wiki.Render.Html;
Declare the Render_Table procedure
Declare the Render_Table procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0e7078ab349d37c85ba78ab3b91905d17bb467b7
awa/src/awa-modules-reader.adb
awa/src/awa-modules-reader.adb
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with Util.Serialize.Mappers; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- 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.ELContext_Access) is procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access); Reader : Util.Serialize.IO.XML.Parser; MBean : aliased ASF.Beans.Mappers.Managed_Bean; Navigation : aliased ASF.Navigations.Mappers.Nav_Config; Servlet : aliased ASF.Servlets.Mappers.Servlet_Config; procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Reader.Add_Mapping ("faces-config", Mapper); Reader.Add_Mapping ("module", Mapper); Reader.Add_Mapping ("web-app", Mapper); end Add_Mapper; begin Log.Info ("Reading module configuration file {0}", File); Add_Mapper (ASF.Beans.Mappers.Get_Managed_Bean_Mapper); Add_Mapper (ASF.Navigations.Mappers.Get_Navigation_Mapper); Add_Mapper (ASF.Servlets.Mappers.Get_Servlet_Mapper); -- Setup the managed bean context to read the <managed-bean> elements. -- The ELContext is used for parsing EL expressions defined in property values. MBean.Factory := Plugin.Factory'Unchecked_Access; MBean.Context := Context; ASF.Beans.Mappers.Config_Mapper.Set_Context (Ctx => Reader, Element => MBean'Unchecked_Access); -- Setup the navigation context to read the <navigation-rule> elements. Navigation.Handler := Plugin.App.Get_Navigation_Handler; ASF.Navigations.Mappers.Case_Mapper.Set_Context (Ctx => Reader, Element => Navigation'Unchecked_Access); Servlet.Handler := Plugin.App.all'Unchecked_Access; ASF.Servlets.Mappers.Servlet_Mapper.Set_Context (Ctx => Reader, Element => Servlet'Unchecked_Access); Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end AWA.Modules.Reader;
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- 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.ELContext_Access) is Reader : Util.Serialize.IO.XML.Parser; Nav : constant ASF.Navigations.Navigation_Handler_Access := Plugin.App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, Plugin.Factory'Unchecked_Access, Context); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, Plugin.App.all'Unchecked_Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); begin Log.Info ("Reading module configuration file {0}", File); Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end AWA.Modules.Reader;
Update Read_Configuration to use the new XXX_Config generic packages.
Update Read_Configuration to use the new XXX_Config generic packages.
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
766aa557be39e1c4ec23c3325a0fb17a05d9dc5a
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- 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.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is 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; Reader : in out MAT.Readers.Manager_Base'Class); -- 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); -- 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 -- 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); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- 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.Frames; with MAT.Readers; 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; Total_Alloc : MAT.Types.Target_Size; Total_Free : MAT.Types.Target_Size; Malloc_Count : Natural; Free_Count : Natural; Realloc_Count : Natural; 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; Reader : in out MAT.Readers.Manager_Base'Class); -- 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); -- 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 -- 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); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Define the Memory_Stat type to collect global statistics
Define the Memory_Stat type to collect global statistics
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
693523be35dbbeecc6208f82e50de084e67331fb
src/natools-smaz.adb
src/natools-smaz.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz is use type Ada.Streams.Stream_Element_Offset; function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String with Pre => Index <= Dict.Dict_Last; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural); function To_String (Data : in Ada.Streams.Stream_Element_Array) return String; ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String is First : constant Positive := Dict.Offsets (Index); Last : Natural := Dict.Values'Last; begin if Index + 1 in Dict.Offsets'Range then Last := Dict.Offsets (Index + 1) - 1; end if; return Dict.Values (First .. Last); end Dict_Entry; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural) is I : Ada.Streams.Stream_Element; N : Natural; begin Index := Ada.Streams.Stream_Element'Last; Length := 0; for Last in reverse Template'Range loop N := Dict.Hash (Template (Template'First .. Last)); if N <= Natural (Dict.Dict_Last) then I := Ada.Streams.Stream_Element (N); if Dict_Entry (Dict, I) = Template (Template'First .. Last) then Index := I; Length := 1 + Last - Template'First; return; end if; end if; end loop; end Find_Entry; function To_String (Data : in Ada.Streams.Stream_Element_Array) return String is begin return Result : String (1 .. Data'Length) do for I in Result'Range loop Result (I) := Character'Val (Data (Data'First + Ada.Streams.Stream_Element_Offset (I - 1))); end loop; end return; end To_String; ---------------------- -- Public Interface -- ---------------------- function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; begin if Dict.Variable_Length_Verbatim then return Ada.Streams.Stream_Element_Count (Input'Length + 2 * (Input'Length + Verbatim2_Max_Size - 1) / Verbatim2_Max_Size); else return Ada.Streams.Stream_Element_Count (Input'Length + (Input'Length + Verbatim1_Max_Size - 1) / Verbatim1_Max_Size); end if; end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Entry; Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Length : Natural; Word : Ada.Streams.Stream_Element; procedure Find_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Word, Length); end Find_Entry; begin Output_Last := Output_Buffer'First - 1; Find_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Word; Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length, Block_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; Verbatim_Encode : while Verbatim_Length > 0 loop if Dict.Variable_Length_Verbatim and then Verbatim_Length > Verbatim1_Max_Size then Block_Length := Natural'Min (Verbatim_Length, Verbatim2_Max_Size); Output_Buffer (Output_Last + 1) := Ada.Streams.Stream_Element'Last; Output_Buffer (Output_Last + 2) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Output_Last := Output_Last + 2; else Block_Length := Natural'Min (Verbatim_Length, Verbatim1_Max_Size); Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Dict.Variable_Length_Verbatim)); end if; Verbatim_Copy : for I in Beginning .. Beginning + Block_Length - 1 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Character'Pos (Input (I)); end loop Verbatim_Copy; Verbatim_Length := Verbatim_Length - Block_Length; Beginning := Beginning + Block_Length; end loop Verbatim_Encode; end Verbatim_Block; end loop Main_Loop; end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Result := Result + Dict_Entry (Dict, Input_Byte)'Length; Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Result := Result + Positive (Verbatim_Length); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is procedure Append (S : in String); procedure Append (S : in Ada.Streams.Stream_Element_Array); procedure Append (S : in String) is begin Output_Buffer (Output_Last + 1 .. Output_Last + S'Length) := S; Output_Last := Output_Last + S'Length; end Append; procedure Append (S : in Ada.Streams.Stream_Element_Array) is begin Append (To_String (S)); end Append; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Append (Dict_Entry (Dict, Input_Byte)); Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Append (Input (Input_Index + 1 .. Input_Index + Verbatim_Length)); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; end Decompress; end Natools.Smaz;
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz is use type Ada.Streams.Stream_Element_Offset; function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String with Pre => Index <= Dict.Dict_Last; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural); function To_String (Data : in Ada.Streams.Stream_Element_Array) return String; function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count; ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String is First : constant Positive := Dict.Offsets (Index); Last : Natural := Dict.Values'Last; begin if Index + 1 in Dict.Offsets'Range then Last := Dict.Offsets (Index + 1) - 1; end if; return Dict.Values (First .. Last); end Dict_Entry; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural) is I : Ada.Streams.Stream_Element; N : Natural; begin Index := Ada.Streams.Stream_Element'Last; Length := 0; for Last in reverse Template'Range loop N := Dict.Hash (Template (Template'First .. Last)); if N <= Natural (Dict.Dict_Last) then I := Ada.Streams.Stream_Element (N); if Dict_Entry (Dict, I) = Template (Template'First .. Last) then Index := I; Length := 1 + Last - Template'First; return; end if; end if; end loop; end Find_Entry; function To_String (Data : in Ada.Streams.Stream_Element_Array) return String is begin return Result : String (1 .. Data'Length) do for I in Result'Range loop Result (I) := Character'Val (Data (Data'First + Ada.Streams.Stream_Element_Offset (I - 1))); end loop; end return; end To_String; function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Original_Size); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Dict.Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim1_Max_Size; begin Overhead := Overhead + Full_Blocks; end; return Overhead + Ada.Streams.Stream_Element_Count (Original_Size); end Verbatim_Size; ---------------------- -- Public Interface -- ---------------------- function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is begin return Verbatim_Size (Dict, Input'Length); end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Entry; Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Length : Natural; Word : Ada.Streams.Stream_Element; procedure Find_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Word, Length); end Find_Entry; Previous_Verbatim_Beginning : Natural := 0; Previous_Verbatim_Last : Ada.Streams.Stream_Element_Offset := 0; begin Output_Last := Output_Buffer'First - 1; Find_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Word; Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length, Block_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; if Previous_Verbatim_Beginning > 0 and then Output_Last + Verbatim_Size (Dict, Verbatim_Length) > Previous_Verbatim_Last + Verbatim_Size (Dict, Input_Index - Previous_Verbatim_Beginning) then Beginning := Previous_Verbatim_Beginning; Output_Last := Previous_Verbatim_Last; Verbatim_Length := Input_Index - Beginning; else Previous_Verbatim_Beginning := Beginning; Previous_Verbatim_Last := Output_Last; end if; Verbatim_Encode : while Verbatim_Length > 0 loop if Dict.Variable_Length_Verbatim and then Verbatim_Length > Verbatim1_Max_Size then Block_Length := Natural'Min (Verbatim_Length, Verbatim2_Max_Size); Output_Buffer (Output_Last + 1) := Ada.Streams.Stream_Element'Last; Output_Buffer (Output_Last + 2) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Output_Last := Output_Last + 2; else Block_Length := Natural'Min (Verbatim_Length, Verbatim1_Max_Size); Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Dict.Variable_Length_Verbatim)); end if; Verbatim_Copy : for I in Beginning .. Beginning + Block_Length - 1 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Character'Pos (Input (I)); end loop Verbatim_Copy; Verbatim_Length := Verbatim_Length - Block_Length; Beginning := Beginning + Block_Length; end loop Verbatim_Encode; end Verbatim_Block; end loop Main_Loop; end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Result := Result + Dict_Entry (Dict, Input_Byte)'Length; Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Result := Result + Positive (Verbatim_Length); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is procedure Append (S : in String); procedure Append (S : in Ada.Streams.Stream_Element_Array); procedure Append (S : in String) is begin Output_Buffer (Output_Last + 1 .. Output_Last + S'Length) := S; Output_Last := Output_Last + S'Length; end Append; procedure Append (S : in Ada.Streams.Stream_Element_Array) is begin Append (To_String (S)); end Append; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Append (Dict_Entry (Dict, Input_Byte)); Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Append (Input (Input_Index + 1 .. Input_Index + Verbatim_Length)); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; end Decompress; end Natools.Smaz;
merge verbatim blocks when it improves compression
smaz: merge verbatim blocks when it improves compression
Ada
isc
faelys/natools
4996dfb56a193d616e8abb96ee932a344720baf8
regtests/wiki-parsers-tests.adb
regtests/wiki-parsers-tests.adb
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x" & CR & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x" & CR & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
Update the unit tests
Update the unit tests
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bf1a679ec343b22823d909f8493a5fa9f25ff330
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Render.Html; with Wiki.Writers; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write (Content); end Write; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Element (Name, Content); end Write_Wide_Element; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- 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.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.Parsers.SYNTAX_MEDIA_WIKI; else return Wiki.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- 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.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Link_Renderer_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Link_Renderer_Access; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Writer (Html'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- Return true if the link is an absolute link. -- ------------------------------ function Is_Link_Absolute (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String) return Boolean is begin return Element (Link, 1) = '/' or else Starts_With (Link, "http://") or else Starts_With (Link, "https://"); end Is_Link_Absolute; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Renderer.Is_Link_Absolute (Link) then URI := Link; else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- 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 Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); 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 Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Render.Html; with Wiki.Writers; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write (Content); end Write; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Element (Name, Content); end Write_Wide_Element; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- 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.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.Parsers.SYNTAX_MEDIA_WIKI; else return Wiki.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- 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.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Link_Renderer_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Link_Renderer_Access; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Writer (Html'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- Return true if the link is an absolute link. -- ------------------------------ function Is_Link_Absolute (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String) return Boolean is pragma Unreferenced (Renderer); begin return Element (Link, 1) = '/' or else Starts_With (Link, "http://") or else Starts_With (Link, "https://"); end Is_Link_Absolute; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Renderer.Is_Link_Absolute (Link) then URI := Link; else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- 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 Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); 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 Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4d8cb21c304a1ccf3409688fad9ff46ec134bd86
awa/src/awa-components-wikis.ads
awa/src/awa-components-wikis.ads
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- 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.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Parsers; 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; -- ------------------------------ -- 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.Parsers.Wiki_Syntax_Type; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Parsers; with Wiki.Render; 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.Parsers.Wiki_Syntax_Type; -- 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.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; type Link_Renderer_Bean is new Util.Beans.Basic.Readonly_Bean and Wiki.Render.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 Unbounded_Wide_Wide_String; 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; -- 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 Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; 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 the Link_Renderer_Bean and override all the Bean and Link_Renderer operations
Declare the Link_Renderer_Bean and override all the Bean and Link_Renderer operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
36d048deed1a37d22d5a647373b210b3d63b9991
src/util-serialize-io.ads
src/util-serialize-io.ads
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 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.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Log.Loggers; with Util.Nullables; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- Write the attribute with a null value. procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write an entity with a null value. procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is abstract; procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Reader is limited interface; -- Start a document. procedure Start_Document (Stream : in out Reader) is null; -- Finish a document. procedure End_Document (Stream : in out Reader) is null; -- 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. procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is abstract; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is abstract; type Parser is abstract new Util.Log.Logging with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); private type Parser is abstract new Util.Log.Logging with record Error_Flag : Boolean := False; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 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.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Log.Loggers; with Util.Nullables; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- Write the attribute with a null value. procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_String); procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Time); procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Boolean); procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Integer); procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Long); -- Write an entity with a null value. procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is abstract; procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Reader is limited interface; -- Start a document. procedure Start_Document (Stream : in out Reader) is null; -- Finish a document. procedure End_Document (Stream : in out Reader) is null; -- 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. procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is abstract; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is abstract; type Parser is abstract new Util.Log.Logging with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); private type Parser is abstract new Util.Log.Logging with record Error_Flag : Boolean := False; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
Define several Write_Entity operations to handle Nullable types
Define several Write_Entity operations to handle Nullable types
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
31bc4446fdf527cbeda86878c4c77741555e0e9c
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline_Always (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline_Always (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline_Always (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline_Always (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline_Always (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Change Inline_Always into Inline pragma since some old Ada compiler fail
Change Inline_Always into Inline pragma since some old Ada compiler fail
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
07c4a39c65becf7802b54c099c6e6e132c4f5162
src/util-strings.adb
src/util-strings.adb
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Returns True if the source string ends with the given suffix. -- ------------------------------ function Ends_With (Source : in String; Suffix : in String) return Boolean is begin return Source'Length >= Suffix'Length and then Source (Source'Last - Suffix'Length + 1 .. Source'Last) = Suffix; end Ends_With; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
Implement the Ends_With function
Implement the Ends_With function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cd5fab28533ed77bbb59d5c8d4a2d470ca3a3b99
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Attributes is -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_UString (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Wiki.Strings.Null_UString; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Wiki.Strings.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Name, Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString) is begin Append (List, Wiki.Strings.To_WString (Name), Wiki.Strings.To_WString (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString) is Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Attributes is -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Wiki.Strings.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Name, Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString) is Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
Remove Get_Unbounded_Wide_Value, Append and Get_Attribute operation
Remove Get_Unbounded_Wide_Value, Append and Get_Attribute operation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
310c3fbc22597188742ba84a167378909abaad34
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); end ADO.Drivers.Tests;
Declare the Test_Set_Connection procedure
Declare the Test_Set_Connection procedure
Ada
apache-2.0
stcarrez/ada-ado
752bd575b025878c656ed630d0386349ca37e3fa
regtests/ado-queries-tests.ads
regtests/ado-queries-tests.ads
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- 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.Tests; package ADO.Queries.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Load_Queries (T : in out Test); -- Test the Initialize operation called several times procedure Test_Initialize (T : in out Test); -- Test the Set_Query operation. procedure Test_Set_Query (T : in out Test); -- Test the Set_Limit operation. procedure Test_Set_Limit (T : in out Test); end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Queries.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Load_Queries (T : in out Test); -- Test the Initialize operation called several times procedure Test_Initialize (T : in out Test); -- Test the Set_Query operation. procedure Test_Set_Query (T : in out Test); -- Test the Set_Limit operation. procedure Test_Set_Limit (T : in out Test); -- Test the Find_Query operation. procedure Test_Find_Query (T : in out Test); end ADO.Queries.Tests;
Declare the Test_Find_Query test
Declare the Test_Find_Query test
Ada
apache-2.0
stcarrez/ada-ado
5d608691fd4cd5ffd98038c1de416db2ddbe9dfb
matp/src/mat-targets-probes.ads
matp/src/mat-targets-probes.ads
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Target_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Target_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type); end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; Frames : MAT.Frames.Targets.Target_Frames_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Target_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Target_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type); end MAT.Targets.Probes;
Add the Frames pointer to the Process_Probe_Type
Add the Frames pointer to the Process_Probe_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
481ba435f0dab977e7f866ed3b39d77f11af4c03
awa/regtests/awa-commands-tests.ads
awa/regtests/awa-commands-tests.ads
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); -- Test the list -u command. procedure Test_List_Users (T : in out Test); -- Test the list -s command. procedure Test_List_Sessions (T : in out Test); -- Test the list -j command. procedure Test_List_Jobs (T : in out Test); -- Test the command with a secure keystore configuration. procedure Test_Secure_Configuration (T : in out Test); -- Test the command with various logging options. procedure Test_Verbose_Command (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); -- Test the list -u command. procedure Test_List_Users (T : in out Test); -- Test the list -s command. procedure Test_List_Sessions (T : in out Test); -- Test the list -j command. procedure Test_List_Jobs (T : in out Test); -- Test the command with a secure keystore configuration. procedure Test_Secure_Configuration (T : in out Test); procedure Test_Secure_Configuration_2 (T : in out Test); -- Test the command with various logging options. procedure Test_Verbose_Command (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
Declare the Test_Secure_Configuration_2 procedure
Declare the Test_Secure_Configuration_2 procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
aa8c2203a22a1d219f1ea64965bbede340c83ebe
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- 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.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- 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.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ procedure Do_Request_Token (App : in Application; URI : in String; Data : in String; Cred : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1)); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); Cred.Access_Token := P.Get ("access_token"); Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", "")); Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", "")); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return; end if; end; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end Do_Request_Token; -- ------------------------------ -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=password" & "&" & Security.OAuth.USERNAME & "=" & Username & "&" & Security.OAuth.PASSWORD & "=" & Password & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0} - resource owner password", URI); Do_Request_Token (App, URI, Data, Token); end Request_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
Implement the Do_Request_Token procedure to make a OAuth grant request Implement the Request_Token RFC 6749: 4.3. Resource Owner Password Credentials Grant
Implement the Do_Request_Token procedure to make a OAuth grant request Implement the Request_Token RFC 6749: 4.3. Resource Owner Password Credentials Grant
Ada
apache-2.0
stcarrez/ada-security
fae6c5b39317a8b404bad9e9c1b481d25bf3cd4b
awa/src/awa-commands.ads
awa/src/awa-commands.ads
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1f75cb5f92bd5ed8b546955ba065ef30d8531ef7
src/sys/os-win32/util-systems-constants.ads
src/sys/os-win32/util-systems-constants.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000400#; O_EXCL : constant Interfaces.C.int := 8#002000#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#000010#; DLL_OPTIONS : constant String := ""; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000400#; O_EXCL : constant Interfaces.C.int := 8#002000#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#000010#; O_CLOEXEC : constant Interfaces.C.int := 0; O_SYNC : constant Interfaces.C.int := 0; O_DIRECT : constant Interfaces.C.int := 0; DLL_OPTIONS : constant String := ""; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
Fix O_CLOEXEC undefined in keystore-io-files.adb (win32)
Fix O_CLOEXEC undefined in keystore-io-files.adb (win32)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
58308abb68c9053f350f6f3374303ef24098cb99
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- 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 Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- 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 Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); end Wiki.Render.Html;
Declare Render_Link procedure
Declare Render_Link procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cefd6831cd5257d920e9f4d29e9a60f9974ffd3f
src/asf-locales.adb
src/asf-locales.adb
----------------------------------------------------------------------- -- asf-locales -- Locale support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with Ada.Strings.Unbounded; package body ASF.Locales is use Util.Properties.Bundles; type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record Loader : Loader_Access; Scope : ASF.Beans.Scope_Type; Name : String (1 .. Len); end record; type Locale_Binding_Access is access all Locale_Binding; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); -- ------------------------------ -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. -- ------------------------------ procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class) is Names : constant Util.Properties.Name_Array := Config.Get_Names ("bundle.var."); Dir : constant String := Config.Get ("bundle.dir", "bundles"); begin Util.Properties.Bundles.Initialize (Fac.Factory, Dir); for I in Names'Range loop declare Name : Util.Properties.Value renames Names (I); Value : constant String := Config.Get (Name); Bundle : constant String := Ada.Strings.Unbounded.To_String (Name); begin Register (Fac, Beans, Bundle (Bundle'First + 11 .. Bundle'Last), Value); end; end loop; end Initialize; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale is use Util.Locales; use type ASF.Requests.Quality_Type; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type); Found_Locale : Util.Locales.Locale := Fac.Default_Locale; Found_Quality : ASF.Requests.Quality_Type := 0.0; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type) is begin if Found_Quality >= Quality then return; end if; for I in 1 .. Fac.Nb_Locales loop -- We need a match on the language. The variant/country can be ignored and will -- be honored by the resource bundle. if Fac.Locales (I) = Locale or Get_Language (Fac.Locales (I)) = Get_Language (Locale) then Found_Locale := Locale; Found_Quality := Quality; return; end if; end loop; end Process_Locales; begin if Fac.Nb_Locales > 0 then Req.Accept_Locales (Process_Locales'Access); end if; return Found_Locale; end Calculate_Locale; procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String) is L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length); P : ASF.Beans.Parameter_Bean_Ref.Ref; begin L.Loader := Fac.Factory'Unchecked_Access; L.Scope := ASF.Beans.REQUEST_SCOPE; L.Name := Bundle; ASF.Beans.Register (Beans, Name, L.all'Access, P); end Register; -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle) is begin Load_Bundle (Factory => Fac.Factory, Locale => Locale, Name => Name, Bundle => Result); end Load_Bundle; -- ------------------------------ -- Get the list of supported locales for this application. -- ------------------------------ function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array is begin return From.Locales (1 .. From.Nb_Locales); end Get_Supported_Locales; -- ------------------------------ -- Add the locale to the list of supported locales. -- ------------------------------ procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Nb_Locales := Into.Nb_Locales + 1; Into.Locales (Into.Nb_Locales) := Locale; end Add_Supported_Locale; -- ------------------------------ -- Get the default locale defined by the application. -- ------------------------------ function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is begin return From.Default_Locale; end Get_Default_Locale; -- ------------------------------ -- Set the default locale defined by the application. -- ------------------------------ procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Default_Locale := Locale; end Set_Default_Locale; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; B : constant Bundle_Access := new Bundle; begin if Context = null then Load_Bundle (Factory => Factory.Loader.all, Locale => "en", Name => Factory.Name, Bundle => B.all); else Load_Bundle (Factory => Factory.Loader.all, Locale => Util.Locales.To_String (Context.Get_Locale), Name => Factory.Name, Bundle => B.all); end if; Result := B.all'Access; end Create; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : Bundle; Name : String) return Util.Beans.Objects.Object is Value : constant String := From.Get (Name, Name); begin return Util.Beans.Objects.To_Object (Value); end Get_Value; end ASF.Locales;
----------------------------------------------------------------------- -- asf-locales -- Locale support -- 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. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with Ada.Strings.Unbounded; package body ASF.Locales is use Util.Properties.Bundles; type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record Loader : Loader_Access; Scope : ASF.Beans.Scope_Type; Name : String (1 .. Len); end record; type Locale_Binding_Access is access all Locale_Binding; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); -- ------------------------------ -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. -- ------------------------------ procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class) is Names : constant Util.Properties.Name_Array := Config.Get_Names ("bundle.var."); Dir : constant String := Config.Get ("bundle.dir", "bundles"); begin Util.Properties.Bundles.Initialize (Fac.Factory, Dir); for I in Names'Range loop declare Name : Util.Properties.Value renames Names (I); Value : constant String := Config.Get (Name); Bundle : constant String := Ada.Strings.Unbounded.To_String (Name); begin Register (Fac, Beans, Bundle (Bundle'First + 11 .. Bundle'Last), Value); end; end loop; end Initialize; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale is use Util.Locales; use type ASF.Requests.Quality_Type; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type); Found_Locale : Util.Locales.Locale := Fac.Default_Locale; Found_Quality : ASF.Requests.Quality_Type := 0.0; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type) is begin if Found_Quality >= Quality then return; end if; for I in 1 .. Fac.Nb_Locales loop -- We need a match on the language. The variant/country can be ignored and will -- be honored by the resource bundle. if Fac.Locales (I) = Locale or Get_Language (Fac.Locales (I)) = Get_Language (Locale) then Found_Locale := Locale; Found_Quality := Quality; return; end if; end loop; end Process_Locales; begin if Fac.Nb_Locales > 0 then Req.Accept_Locales (Process_Locales'Access); end if; return Found_Locale; end Calculate_Locale; procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String) is L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length); P : ASF.Beans.Parameter_Bean_Ref.Ref; begin L.Loader := Fac.Factory'Unchecked_Access; L.Scope := ASF.Beans.REQUEST_SCOPE; L.Name := Bundle; ASF.Beans.Register (Beans, Name, L.all'Access, P); end Register; -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle) is begin Load_Bundle (Factory => Fac.Factory, Locale => Locale, Name => Name, Bundle => Result); end Load_Bundle; -- ------------------------------ -- Get the list of supported locales for this application. -- ------------------------------ function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array is begin return From.Locales (1 .. From.Nb_Locales); end Get_Supported_Locales; -- ------------------------------ -- Add the locale to the list of supported locales. -- ------------------------------ procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Nb_Locales := Into.Nb_Locales + 1; Into.Locales (Into.Nb_Locales) := Locale; end Add_Supported_Locale; -- ------------------------------ -- Get the default locale defined by the application. -- ------------------------------ function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is begin return From.Default_Locale; end Get_Default_Locale; -- ------------------------------ -- Set the default locale defined by the application. -- ------------------------------ procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Default_Locale := Locale; end Set_Default_Locale; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; B : constant Bundle_Access := new Bundle; begin if Context = null then Load_Bundle (Factory => Factory.Loader.all, Locale => "en", Name => Factory.Name, Bundle => B.all); else Load_Bundle (Factory => Factory.Loader.all, Locale => Util.Locales.To_String (Context.Get_Locale), Name => Factory.Name, Bundle => B.all); end if; Result := B.all'Access; end Create; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : Bundle; Name : String) return Util.Beans.Objects.Object is Value : constant String := From.Get (Name, Name); begin return Util.Beans.Objects.To_Object (Value); end Get_Value; end ASF.Locales;
Fix indentation style warning
Fix indentation style warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
deea859ccd21d1e6e5b0ee7dacd5d8e98b16efb3
src/asf-locales.adb
src/asf-locales.adb
----------------------------------------------------------------------- -- asf-locales -- Locale support -- 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. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with Ada.Strings.Unbounded; package body ASF.Locales is use Util.Properties.Bundles; type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record Loader : Loader_Access; Scope : ASF.Beans.Scope_Type; Name : String (1 .. Len); end record; type Locale_Binding_Access is access all Locale_Binding; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); -- ------------------------------ -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. -- ------------------------------ procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class) is Names : constant Util.Properties.Name_Array := Config.Get_Names ("bundle.var."); Dir : constant String := Config.Get ("bundle.dir", "bundles"); begin Util.Properties.Bundles.Initialize (Fac.Factory, Dir); for I in Names'Range loop declare Name : Util.Properties.Value renames Names (I); Value : constant String := Config.Get (Name); Bundle : constant String := Ada.Strings.Unbounded.To_String (Name); begin Register (Fac, Beans, Bundle (Bundle'First + 11 .. Bundle'Last), Value); end; end loop; end Initialize; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale is use Util.Locales; use type ASF.Requests.Quality_Type; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type); Found_Locale : Util.Locales.Locale := Fac.Default_Locale; Found_Quality : ASF.Requests.Quality_Type := 0.0; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type) is begin if Found_Quality >= Quality then return; end if; for I in 1 .. Fac.Nb_Locales loop -- We need a match on the language. The variant/country can be ignored and will -- be honored by the resource bundle. if Fac.Locales (I) = Locale or Get_Language (Fac.Locales (I)) = Get_Language (Locale) then Found_Locale := Locale; Found_Quality := Quality; return; end if; end loop; end Process_Locales; begin if Fac.Nb_Locales > 0 then Req.Accept_Locales (Process_Locales'Access); end if; return Found_Locale; end Calculate_Locale; procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String) is L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length); P : ASF.Beans.Parameter_Bean_Ref.Ref; begin L.Loader := Fac.Factory'Unchecked_Access; L.Scope := ASF.Beans.REQUEST_SCOPE; L.Name := Bundle; ASF.Beans.Register (Beans, Name, L.all'Access, P); end Register; -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle) is begin Load_Bundle (Factory => Fac.Factory, Locale => Locale, Name => Name, Bundle => Result); end Load_Bundle; -- ------------------------------ -- Get the list of supported locales for this application. -- ------------------------------ function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array is begin return From.Locales (1 .. From.Nb_Locales); end Get_Supported_Locales; -- ------------------------------ -- Add the locale to the list of supported locales. -- ------------------------------ procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Nb_Locales := Into.Nb_Locales + 1; Into.Locales (Into.Nb_Locales) := Locale; end Add_Supported_Locale; -- ------------------------------ -- Get the default locale defined by the application. -- ------------------------------ function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is begin return From.Default_Locale; end Get_Default_Locale; -- ------------------------------ -- Set the default locale defined by the application. -- ------------------------------ procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Default_Locale := Locale; end Set_Default_Locale; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; B : constant Bundle_Access := new Bundle; begin if Context = null then Load_Bundle (Factory => Factory.Loader.all, Locale => "en", Name => Factory.Name, Bundle => B.all); else Load_Bundle (Factory => Factory.Loader.all, Locale => Util.Locales.To_String (Context.Get_Locale), Name => Factory.Name, Bundle => B.all); end if; Result := B.all'Access; end Create; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : Bundle; Name : String) return Util.Beans.Objects.Object is Value : constant String := From.Get (Name, Name); begin return Util.Beans.Objects.To_Object (Value); end Get_Value; end ASF.Locales;
----------------------------------------------------------------------- -- asf-locales -- Locale support -- 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 Util.Strings.Vectors; with ASF.Contexts.Faces; with Ada.Strings.Unbounded; package body ASF.Locales is use Util.Properties.Bundles; type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record Loader : Loader_Access; Scope : ASF.Beans.Scope_Type; Name : String (1 .. Len); end record; type Locale_Binding_Access is access all Locale_Binding; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); -- ------------------------------ -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. -- ------------------------------ procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class) is Names : Util.Strings.Vectors.Vector; Dir : constant String := Config.Get ("bundle.dir", "bundles"); begin Config.Get_Names (Names, "bundle.var."); Util.Properties.Bundles.Initialize (Fac.Factory, Dir); for Name of Names loop -- I in Names'Range loop declare Value : constant String := Config.Get (Name); begin Register (Fac, Beans, Name (Name'First + 11 .. Name'Last), Value); end; end loop; end Initialize; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale is use Util.Locales; use type ASF.Requests.Quality_Type; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type); Found_Locale : Util.Locales.Locale := Fac.Default_Locale; Found_Quality : ASF.Requests.Quality_Type := 0.0; procedure Process_Locales (Locale : in Util.Locales.Locale; Quality : in ASF.Requests.Quality_Type) is begin if Found_Quality >= Quality then return; end if; for I in 1 .. Fac.Nb_Locales loop -- We need a match on the language. The variant/country can be ignored and will -- be honored by the resource bundle. if Fac.Locales (I) = Locale or Get_Language (Fac.Locales (I)) = Get_Language (Locale) then Found_Locale := Locale; Found_Quality := Quality; return; end if; end loop; end Process_Locales; begin if Fac.Nb_Locales > 0 then Req.Accept_Locales (Process_Locales'Access); end if; return Found_Locale; end Calculate_Locale; procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String) is L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length); P : ASF.Beans.Parameter_Bean_Ref.Ref; begin L.Loader := Fac.Factory'Unchecked_Access; L.Scope := ASF.Beans.REQUEST_SCOPE; L.Name := Bundle; ASF.Beans.Register (Beans, Name, L.all'Access, P); end Register; -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle) is begin Load_Bundle (Factory => Fac.Factory, Locale => Locale, Name => Name, Bundle => Result); end Load_Bundle; -- ------------------------------ -- Get the list of supported locales for this application. -- ------------------------------ function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array is begin return From.Locales (1 .. From.Nb_Locales); end Get_Supported_Locales; -- ------------------------------ -- Add the locale to the list of supported locales. -- ------------------------------ procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Nb_Locales := Into.Nb_Locales + 1; Into.Locales (Into.Nb_Locales) := Locale; end Add_Supported_Locale; -- ------------------------------ -- Get the default locale defined by the application. -- ------------------------------ function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is begin return From.Default_Locale; end Get_Default_Locale; -- ------------------------------ -- Set the default locale defined by the application. -- ------------------------------ procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale) is begin Into.Default_Locale := Locale; end Set_Default_Locale; procedure Create (Factory : in Locale_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; B : constant Bundle_Access := new Bundle; begin if Context = null then Load_Bundle (Factory => Factory.Loader.all, Locale => "en", Name => Factory.Name, Bundle => B.all); else Load_Bundle (Factory => Factory.Loader.all, Locale => Util.Locales.To_String (Context.Get_Locale), Name => Factory.Name, Bundle => B.all); end if; Result := B.all'Access; end Create; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : Bundle; Name : String) return Util.Beans.Objects.Object is Value : constant String := From.Get (Name, Name); begin return Util.Beans.Objects.To_Object (Value); end Get_Value; end ASF.Locales;
Use the new Get_Names procedure from the Util.Properties package
Use the new Get_Names procedure from the Util.Properties package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d9beeb7aa35b4b2f8a57d47899d5fe3b6e9388d1
matp/src/mat-types.ads
matp/src/mat-types.ads
----------------------------------------------------------------------- -- mat-types -- Global types -- 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 Interfaces; package MAT.Types is pragma Preelaborate; type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_64; subtype Target_Size is Interfaces.Unsigned_64; subtype Target_Offset is Interfaces.Unsigned_64; type Target_Tick_Ref is new Uint64; type Target_Thread_Ref is new Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Target_Tick_Ref; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String; -- Format the target time to a printable representation. function Tick_Image (Value : in Target_Tick_Ref) return String; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref; end MAT.Types;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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 Interfaces; package MAT.Types is pragma Preelaborate; type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_64; subtype Target_Size is Interfaces.Unsigned_64; subtype Target_Offset is Interfaces.Unsigned_64; type Target_Tick_Ref is new Uint64; type Target_Thread_Ref is new Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Target_Tick_Ref; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String; -- Format the target time to a printable representation. function Tick_Image (Value : in Target_Tick_Ref) return String; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref; -- Convert the hexadecimal string into an unsigned integer. function Hex_Value (Value : in String) return Uint64; end MAT.Types;
Declare the Hex_Value function
Declare the Hex_Value function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
253635a6c52052e40cfd25ef6cca7a204dca7a57
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is -- Minimum length for the server private key (160 bits min length). -- (See NIST Special Publication 800-107) MIN_KEY_LENGTH : constant Positive := 20; Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; -- Decode the expiration date that was extracted from the token. function Parse_Expire (Expire : in String) return Ada.Calendar.Time; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. The realm also returns in the grant the user principal that -- identifies the user. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is -- Minimum length for the server private key (160 bits min length). -- (See NIST Special Publication 800-107) MIN_KEY_LENGTH : constant Positive := 20; Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; -- Decode the expiration date that was extracted from the token. function Parse_Expire (Expire : in String) return Ada.Calendar.Time; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
5d376ce26e6445a0e816b692f58e6663a7437338
testcases/execute_dynabound/execute_dynabound.adb
testcases/execute_dynabound/execute_dynabound.adb
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with Ada.Calendar; with AdaBase.Results.Sets; with Interfaces; procedure Execute_Dynabound is package CON renames Connect; package TIO renames Ada.Text_IO; package AR renames AdaBase.Results; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; package CAL renames Ada.Calendar; package Byte_Io is new Ada.Text_Io.Modular_Io (Interfaces.Unsigned_8); type halfbyte is mod 2 ** 4; procedure dump_result; function halfbyte_to_hex (value : halfbyte) return Character; function convert_chain (chain : AR.chain) return String; function convert_set (set : AR.settype) return String; function pad (S : String; Slen : Natural) return String; function pad (S : String; Slen : Natural) return String is field : String (1 .. Slen) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; function halfbyte_to_hex (value : halfbyte) return Character is zero : constant Natural := Character'Pos ('0'); alpham10 : constant Natural := Character'Pos ('A') - 10; begin case value is when 0 .. 9 => return Character'Val (zero + Natural (value)); when others => return Character'Val (alpham10 + Natural (value)); end case; end halfbyte_to_hex; function convert_chain (chain : AR.chain) return String is use type AR.nbyte1; blocks : constant Natural := chain'Length; mask_ones : constant AR.nbyte1 := 16#0F#; work_4bit : halfbyte; result : String (1 .. blocks * 3 - 1) := (others => ' '); index : Natural := 0; fullbyte : Interfaces.Unsigned_8; begin for x in Positive range 1 .. blocks loop index := index + 1; fullbyte := Interfaces.Unsigned_8 (chain (x)); fullbyte := Interfaces.Shift_Right (fullbyte, 4); work_4bit := halfbyte (fullbyte); result (index) := halfbyte_to_hex (work_4bit); index := index + 1; work_4bit := halfbyte (chain (x) and mask_ones); result (index) := halfbyte_to_hex (work_4bit); index := index + 1; end loop; if blocks = 0 then return "(empty)"; end if; return result; end convert_chain; function convert_set (set : AR.settype) return String is result : CT.Text; begin for x in set'Range loop if not CT.IsBlank (set (x).enumeration) then if x > set'First then CT.SU.Append (result, ","); end if; CT.SU.Append (result, set (x).enumeration); end if; end loop; return CT.USS (result); end convert_set; procedure dump_result is row : ARS.DataRow_Access; numcols : constant Natural := CON.STMT.column_count; begin loop exit when not CON.STMT.fetch_next (row); TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put (CT.zeropad (c, 2) & ". "); TIO.Put (pad (CON.STMT.column_name (c), 16)); TIO.Put (pad (CON.STMT.column_native_type (c)'Img, 15)); case CON.STMT.column_native_type (c) is when AdaBase.ft_chain => TIO.Put_Line (convert_chain (row.column (c).as_chain)); when others => TIO.Put_Line (row.column (c).as_string); end case; end loop; end loop; TIO.Put_Line (""); end dump_result; cols : constant String := "id_nbyte3, nbyte0, " & "nbyte1, byte2, byte4, nbyte8, real9, real18, " & "exact_decimal, my_date, my_timestamp, " & "my_time, my_year, my_tinytext, enumtype, " & "settype, my_varbinary, my_blob"; sql3 : constant String := "INSERT INTO all_types (" & cols & ") VALUES " & "(?,?, ?,?,?,?,?,?, ?,?,?, ?,?,?,?, ?,?,?)"; sql1 : constant String := "SELECT " & cols & " FROM all_types " & "WHERE id_nbyte3 > 8"; begin declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare numrows : AdaBase.AffectedRows; begin numrows := CON.DR.execute ("DELETE FROM all_types WHERE id_nbyte3 > 8"); if Natural (numrows) > 0 then CON.DR.commit; end if; end; declare vals1 : constant String := "20|1|150|-10|-90000|3200100|87.2341|" & "15555.213792831213|875.44|2014-10-20|2000-03-25 15:15:00|" & "20:18:13|1986|AdaBase is so cool!|green|yellow,black|" & " 0123|456789ABC.,z[]"; vals2 : constant String := "25;0;200;25;22222;50;4.84324982;" & "9234963.123235987;15.79;1910-11-05;2030-12-25 11:59:59;" & "04:00:45;1945;This is what it sounds like when doves cry;" & "red;blue,white;Q|ER;01234" & Character'Val (0) & Character'Val (10) & "789"; good : Boolean := True; begin CON.STMT := CON.DR.prepare (sql3); -- This has to be done only once after the prepare command -- Set the type for each parameter (required for at least MySQL) CON.STMT.assign (1, AR.PARAM_IS_NBYTE_3); CON.STMT.assign (2, AR.PARAM_IS_BOOLEAN); CON.STMT.assign (3, AR.PARAM_IS_NBYTE_1); CON.STMT.assign (4, AR.PARAM_IS_BYTE_2); CON.STMT.assign (5, AR.PARAM_IS_BYTE_4); CON.STMT.assign (6, AR.PARAM_IS_NBYTE_8); CON.STMT.assign (7, AR.PARAM_IS_REAL_9); CON.STMT.assign (8, AR.PARAM_IS_REAL_18); CON.STMT.assign (9, AR.PARAM_IS_REAL_9); CON.STMT.assign (10, AR.PARAM_IS_TIMESTAMP); CON.STMT.assign (11, AR.PARAM_IS_TIMESTAMP); CON.STMT.assign (12, AR.PARAM_IS_TIMESTAMP); CON.STMT.assign (13, AR.PARAM_IS_NBYTE_2); CON.STMT.assign (14, AR.PARAM_IS_TEXTUAL); CON.STMT.assign (15, AR.PARAM_IS_ENUM); CON.STMT.assign (16, AR.PARAM_IS_SET); CON.STMT.assign (17, AR.PARAM_IS_CHAIN); CON.STMT.assign (18, AR.PARAM_IS_CHAIN); good := CON.STMT.execute (vals1); if good then good := CON.STMT.execute (parameters => vals2, delimiter => ';'); end if; if good then CON.DR.commit; else TIO.Put_Line ("statement execution failed"); CON.DR.rollback; end if; end; begin CON.STMT := CON.DR.query (sql1); if CON.STMT.successful then TIO.Put_Line ("Dumping Result from direct statement ..."); dump_result; end if; end; begin CON.STMT := CON.DR.prepare (sql1); if CON.STMT.execute then TIO.Put_Line ("Dumping Result from prepared statement ..."); dump_result; end if; end; TIO.Put_Line ("Note slight differences in real9 and real18 field values"); TIO.Put_Line ("due to rounding differences inherent in the different"); TIO.Put_Line ("retrieval mechanisms of direct and prep stmt results."); CON.DR.disconnect; end Execute_Dynabound;
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with Ada.Calendar; with AdaBase.Results.Sets; with Interfaces; procedure Execute_Dynabound is package CON renames Connect; package TIO renames Ada.Text_IO; package AR renames AdaBase.Results; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; package CAL renames Ada.Calendar; package Byte_Io is new Ada.Text_Io.Modular_Io (Interfaces.Unsigned_8); type halfbyte is mod 2 ** 4; stmt_acc : CON.Stmt_Type_access; procedure dump_result; function halfbyte_to_hex (value : halfbyte) return Character; function convert_chain (chain : AR.chain) return String; function convert_set (set : AR.settype) return String; function pad (S : String; Slen : Natural) return String; function pad (S : String; Slen : Natural) return String is field : String (1 .. Slen) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; function halfbyte_to_hex (value : halfbyte) return Character is zero : constant Natural := Character'Pos ('0'); alpham10 : constant Natural := Character'Pos ('A') - 10; begin case value is when 0 .. 9 => return Character'Val (zero + Natural (value)); when others => return Character'Val (alpham10 + Natural (value)); end case; end halfbyte_to_hex; function convert_chain (chain : AR.chain) return String is use type AR.nbyte1; blocks : constant Natural := chain'Length; mask_ones : constant AR.nbyte1 := 16#0F#; work_4bit : halfbyte; result : String (1 .. blocks * 3 - 1) := (others => ' '); index : Natural := 0; fullbyte : Interfaces.Unsigned_8; begin for x in Positive range 1 .. blocks loop index := index + 1; fullbyte := Interfaces.Unsigned_8 (chain (x)); fullbyte := Interfaces.Shift_Right (fullbyte, 4); work_4bit := halfbyte (fullbyte); result (index) := halfbyte_to_hex (work_4bit); index := index + 1; work_4bit := halfbyte (chain (x) and mask_ones); result (index) := halfbyte_to_hex (work_4bit); index := index + 1; end loop; if blocks = 0 then return "(empty)"; end if; return result; end convert_chain; function convert_set (set : AR.settype) return String is result : CT.Text; begin for x in set'Range loop if not CT.IsBlank (set (x).enumeration) then if x > set'First then CT.SU.Append (result, ","); end if; CT.SU.Append (result, set (x).enumeration); end if; end loop; return CT.USS (result); end convert_set; procedure dump_result is row : ARS.DataRow; numcols : constant Natural := stmt_acc.column_count; begin loop row := stmt_acc.fetch_next; exit when row.data_exhausted; TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put (CT.zeropad (c, 2) & ". "); TIO.Put (pad (stmt_acc.column_name (c), 16)); TIO.Put (pad (stmt_acc.column_native_type (c)'Img, 15)); case stmt_acc.column_native_type (c) is when AdaBase.ft_chain => TIO.Put_Line (convert_chain (row.column (c).as_chain)); when others => TIO.Put_Line (row.column (c).as_string); end case; end loop; end loop; TIO.Put_Line (""); end dump_result; cols : constant String := "id_nbyte3, nbyte0, " & "nbyte1, byte2, byte4, nbyte8, real9, real18, " & "exact_decimal, my_date, my_timestamp, " & "my_time, my_year, my_tinytext, enumtype, " & "settype, my_varbinary, my_blob"; sql3 : constant String := "INSERT INTO all_types (" & cols & ") VALUES " & "(?,?, ?,?,?,?,?,?, ?,?,?, ?,?,?,?, ?,?,?)"; sql1 : constant String := "SELECT " & cols & " FROM all_types " & "WHERE id_nbyte3 > 8"; begin begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare numrows : AdaBase.AffectedRows; begin numrows := CON.DR.execute ("DELETE FROM all_types WHERE id_nbyte3 > 8"); if Natural (numrows) > 0 then CON.DR.commit; end if; end; declare vals1 : constant String := "20|1|150|-10|-90000|3200100|87.2341|" & "15555.213792831213|875.44|2014-10-20|2000-03-25 15:15:00|" & "20:18:13|1986|AdaBase is so cool!|green|yellow,black|" & " 0123|456789ABC.,z[]"; vals2 : constant String := "25;0;200;25;22222;50;4.84324982;" & "9234963.123235987;15.79;1910-11-05;2030-12-25 11:59:59;" & "04:00:45;1945;This is what it sounds like when doves cry;" & "red;blue,white;Q|ER;01234" & Character'Val (0) & Character'Val (10) & "789"; good : Boolean := True; stmt : CON.Stmt_Type := CON.DR.prepare (sql3); begin -- This has to be done only once after the prepare command -- Set the type for each parameter (required for at least MySQL) stmt.assign (1, AR.PARAM_IS_NBYTE_3); stmt.assign (2, AR.PARAM_IS_BOOLEAN); stmt.assign (3, AR.PARAM_IS_NBYTE_1); stmt.assign (4, AR.PARAM_IS_BYTE_2); stmt.assign (5, AR.PARAM_IS_BYTE_4); stmt.assign (6, AR.PARAM_IS_NBYTE_8); stmt.assign (7, AR.PARAM_IS_REAL_9); stmt.assign (8, AR.PARAM_IS_REAL_18); stmt.assign (9, AR.PARAM_IS_REAL_9); stmt.assign (10, AR.PARAM_IS_TIMESTAMP); stmt.assign (11, AR.PARAM_IS_TIMESTAMP); stmt.assign (12, AR.PARAM_IS_TIMESTAMP); stmt.assign (13, AR.PARAM_IS_NBYTE_2); stmt.assign (14, AR.PARAM_IS_TEXTUAL); stmt.assign (15, AR.PARAM_IS_ENUM); stmt.assign (16, AR.PARAM_IS_SET); stmt.assign (17, AR.PARAM_IS_CHAIN); stmt.assign (18, AR.PARAM_IS_CHAIN); good := stmt.execute (vals1); if good then good := stmt.execute (parameters => vals2, delimiter => ';'); end if; if good then CON.DR.commit; else TIO.Put_Line ("statement execution failed"); CON.DR.rollback; end if; end; declare stmt : aliased CON.Stmt_Type := CON.DR.query (sql1); begin if stmt.successful then stmt_acc := stmt'Unchecked_Access; TIO.Put_Line ("Dumping Result from direct statement ..."); dump_result; end if; end; declare stmt : aliased CON.Stmt_Type := CON.DR.prepare (sql1); begin if stmt.execute then stmt_acc := stmt'Unchecked_Access; TIO.Put_Line ("Dumping Result from prepared statement ..."); dump_result; end if; end; TIO.Put_Line ("Note slight differences in real9 and real18 field values"); TIO.Put_Line ("due to rounding differences inherent in the different"); TIO.Put_Line ("retrieval mechanisms of direct and prep stmt results."); CON.DR.disconnect; end Execute_Dynabound;
fix execute_dynabound test case
fix execute_dynabound test case
Ada
isc
jrmarino/AdaBase
ec084716b9199c3b823ecbec044a841f2baa5c2d
src/util-dates-iso8601.ads
src/util-dates-iso8601.ads
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Dates.ISO8601 is -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. function Value (Date : in String) return Ada.Calendar.Time; -- Return the ISO8601 date. function Image (Date : in Ada.Calendar.Time) return String; function Image (Date : in Date_Record) return String; end Util.Dates.ISO8601;
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Dates.ISO8601 is type Precision_Type is (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, SUBSECOND); -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. function Value (Date : in String) return Ada.Calendar.Time; -- Return the ISO8601 date. function Image (Date : in Ada.Calendar.Time) return String; function Image (Date : in Date_Record) return String; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String; function Image (Date : in Date_Record; Precision : in Precision_Type) return String; end Util.Dates.ISO8601;
Declare Precision_Type enumeration Declare new Image function
Declare Precision_Type enumeration Declare new Image function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
dfc768ec870895664ad0fe4eea411845811994df
src/util-streams-texts.ads
src/util-streams-texts.ads
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; -- === Texts === -- The <tt>Util.Streams.Texts</tt> package implements text oriented input and output streams. -- The <tt>Print_Stream</tt> type extends the <tt>Output_Buffer_Stream</tt> to allow writing -- text content. -- -- The <tt>Reader_Stream</tt> package extends the <tt>Input_Buffer_Stream</tt> and allows to -- read text content. package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
Document the streams framework
Document the streams framework
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c5eda40442b2d73c21fb5d5778fd8e254b3dcbfb
regtests/gen-testsuite.adb
regtests/gen-testsuite.adb
----------------------------------------------------------------------- -- gen-testsuite -- Testsuite for gen -- 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.Directories; with Ada.Strings.Unbounded; with Gen.Artifacts.XMI.Tests; with Gen.Integration.Tests; package body Gen.Testsuite is Tests : aliased Util.Tests.Test_Suite; Dir : Ada.Strings.Unbounded.Unbounded_String; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Gen.Artifacts.XMI.Tests.Add_Tests (Result); Gen.Integration.Tests.Add_Tests (Result); return Result; end Suite; -- ------------------------------ -- Get the test root directory. -- ------------------------------ function Get_Test_Directory return String is begin return Ada.Strings.Unbounded.To_String (Dir); end Get_Test_Directory; procedure Initialize (Props : in Util.Properties.Manager) is begin Dir := Ada.Strings.Unbounded.To_Unbounded_String (Ada.Directories.Current_Directory); end Initialize; end Gen.Testsuite;
----------------------------------------------------------------------- -- gen-testsuite -- Testsuite for gen -- 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.Directories; with Ada.Strings.Unbounded; with Gen.Artifacts.XMI.Tests; with Gen.Integration.Tests; package body Gen.Testsuite is Tests : aliased Util.Tests.Test_Suite; Dir : Ada.Strings.Unbounded.Unbounded_String; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Gen.Artifacts.XMI.Tests.Add_Tests (Result); Gen.Integration.Tests.Add_Tests (Result); return Result; end Suite; -- ------------------------------ -- Get the test root directory. -- ------------------------------ function Get_Test_Directory return String is begin return Ada.Strings.Unbounded.To_String (Dir); end Get_Test_Directory; procedure Initialize (Props : in Util.Properties.Manager) is pragma Unreferenced (Props); begin Dir := Ada.Strings.Unbounded.To_Unbounded_String (Ada.Directories.Current_Directory); end Initialize; end Gen.Testsuite;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
1317c46ac0e8fb91d2c09b7bfc476ddc7624e7d8
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, 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.Fixed; with Ada.Strings.Maps; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is use type Ada.Strings.Maps.Character_Set; function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); Marker : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" .,;:!?)") or Ada.Strings.Maps.To_Set (ASCII.HT) or Ada.Strings.Maps.To_Set (ASCII.VT) or Ada.Strings.Maps.To_Set (ASCII.CR) or Ada.Strings.Maps.To_Set (ASCII.LF); -- ------------------------------ -- 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 if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; 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; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Start : Natural := Text'First; Last : Natural := Text'Last; Link : Util.Strings.Maps.Cursor; Pos : Natural; begin Log.Debug ("Auto link |{0}|", Text); loop -- Emit spaces at beginning of line or words. while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop Ada.Text_IO.Put (File, Text (Start)); Start := Start + 1; end loop; exit when Start > Text'Last; -- Find a possible link. Link := Formatter.Links.Find (Text (Start .. Last)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Start .. Last)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Start := Last + 1; Last := Text'Last; else Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker, Going => Ada.Strings.Backward); if Pos = 0 then Ada.Text_IO.Put (File, Text (Start .. Last)); Start := Last + 1; Last := Text'Last; else Last := Pos - 1; -- Skip spaces at end of words for the search. while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop Last := Last - 1; end loop; end if; end if; end loop; end Write_Text_Auto_Links; -- ------------------------------ -- 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 -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last)); return; end if; Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; 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 Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then 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, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); 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, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => if Formatter.Mode /= L_START_CODE then Formatter.Mode := L_TEXT; end if; 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); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Maps; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is use type Ada.Strings.Maps.Character_Set; function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); Marker : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" .,;:!?)") or Ada.Strings.Maps.To_Set (ASCII.HT) or Ada.Strings.Maps.To_Set (ASCII.VT) or Ada.Strings.Maps.To_Set (ASCII.CR) or Ada.Strings.Maps.To_Set (ASCII.LF); -- ------------------------------ -- 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 if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; 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; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Start : Natural := Text'First; Last : Natural := Text'Last; Link : Util.Strings.Maps.Cursor; Pos : Natural; begin Log.Debug ("Auto link |{0}|", Text); loop -- Emit spaces at beginning of line or words. while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop Ada.Text_IO.Put (File, Text (Start)); Start := Start + 1; end loop; exit when Start > Text'Last; -- Find a possible link. Link := Formatter.Links.Find (Text (Start .. Last)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Start .. Last)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Start := Last + 1; Last := Text'Last; else Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker, Going => Ada.Strings.Backward); if Pos = 0 then Ada.Text_IO.Put (File, Text (Start .. Last)); Start := Last + 1; Last := Text'Last; else Last := Pos - 1; -- Skip spaces at end of words for the search. while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop Last := Last - 1; end loop; end if; end if; end loop; end Write_Text_Auto_Links; -- ------------------------------ -- 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; Link : Util.Strings.Maps.Cursor; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last)); return; end if; Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; 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 Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then 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, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Link := Formatter.Links.Find (Text (Pos .. Last_Pos)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, "]"); else Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos)); end if; 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, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => if Formatter.Mode /= L_START_CODE then Formatter.Mode := L_TEXT; end if; 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); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Fix generation of markdown links
Fix generation of markdown links
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
c3423d1791d12905ab76c72f7b74fedb018c3587
regtests/util-beans-objects-record_tests.adb
regtests/util-beans-objects-record_tests.adb
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- 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.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Objects.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J - 1); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- 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.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Objects.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J - 1); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Unchecked_Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
Fix compilation error
Fix compilation error
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
667c45a0595d4a2bfca81bec73c3552aabc986c5
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "stat"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "fstat"); end Util.Systems.Os;
Define the Sys_Stat and Sys_Fstat operations
Define the Sys_Stat and Sys_Fstat operations
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
85a4b252e0cdc7a816567c7be40c4a03c531331a
src/gen-model-list.ads
src/gen-model-list.ads
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Basic; with Gen.Model; with Ada.Containers.Vectors; generic type T is new Gen.Model.Definition with private; type T_Access is access all T'Class; package Gen.Model.List is -- Compare the two definitions. function "<" (Left, Right : in T_Access) return Boolean; package Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => T_Access, "=" => "="); package Sorting is new Vectors.Generic_Sorting; subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return T_Access renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; type List_Definition is limited new Util.Beans.Basic.List_Bean with private; -- Get the first item of the list function First (Def : List_Definition) return Cursor; -- Get the number of elements in the list. overriding function Get_Count (From : List_Definition) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : List_Definition) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : List_Definition; Name : String) return Util.Beans.Objects.Object; -- Append the item in the list procedure Append (Def : in out List_Definition; Item : in T_Access); -- Sort the list of items on their names. procedure Sort (List : in out List_Definition); generic with function "<" (Left, Right : T_Access) return Boolean is <>; procedure Sort_On (List : in out List_Definition); -- Find a definition given the name. -- Returns the definition object or null. function Find (Def : in List_Definition; Name : in String) return T_Access; -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)); private type List_Definition is limited new Util.Beans.Basic.List_Bean with record Nodes : Vectors.Vector; Row : Natural := 0; Value_Bean : Util.Beans.Objects.Object; end record; end Gen.Model.List;
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Basic; with Gen.Model; with Ada.Containers.Vectors; with Ada.Iterator_Interfaces; generic type T is new Gen.Model.Definition with private; type T_Access is access all T'Class; package Gen.Model.List is -- Compare the two definitions. function "<" (Left, Right : in T_Access) return Boolean; package Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => T_Access, "=" => "="); package Sorting is new Vectors.Generic_Sorting; subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return T_Access renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; type List_Definition is limited new Util.Beans.Basic.List_Bean with private with Default_Iterator => Iterate, Iterator_Element => T_Access, Constant_Indexing => Element_Value; package List_Iterator is new Ada.Iterator_Interfaces (Cursor, Has_Element); -- Make an iterator for the list. function Iterate (Container : in List_Definition) return List_Iterator.Forward_Iterator'Class; -- Get the iterator element. function Element_Value (Container : in List_Definition; Pos : in Cursor) return T_Access; -- Get the first item of the list function First (Def : List_Definition) return Cursor; -- Get the number of elements in the list. overriding function Get_Count (From : List_Definition) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : List_Definition) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : List_Definition; Name : String) return Util.Beans.Objects.Object; -- Append the item in the list procedure Append (Def : in out List_Definition; Item : in T_Access); -- Sort the list of items on their names. procedure Sort (List : in out List_Definition); generic with function "<" (Left, Right : T_Access) return Boolean is <>; procedure Sort_On (List : in out List_Definition); -- Find a definition given the name. -- Returns the definition object or null. function Find (Def : in List_Definition; Name : in String) return T_Access; -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)); private type List_Definition_Access is access all List_Definition; type List_Definition is limited new Util.Beans.Basic.List_Bean with record Self : List_Definition_Access := List_Definition'Unchecked_Access; Nodes : Vectors.Vector; Row : Natural := 0; Value_Bean : Util.Beans.Objects.Object; end record; type Iterator is limited new List_Iterator.Forward_Iterator with record List : List_Definition_Access; end record; overriding function First (Object : Iterator) return Cursor; overriding function Next (Object : Iterator; Pos : Cursor) return Cursor; end Gen.Model.List;
Change List_Definition to allow using the Ada 2012 iterators - Add necessary aspect definitions, - Instantiate List_Iterator package, - Define Iterate and Element_Value function - Declare private Iterator type with First and Next functions
Change List_Definition to allow using the Ada 2012 iterators - Add necessary aspect definitions, - Instantiate List_Iterator package, - Define Iterate and Element_Value function - Declare private Iterator type with First and Next functions
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
3b6d2a57353ed4095b5fbbf5232ddc6642ee19f8
matp/src/mat-formats.ads
matp/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Tools; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the PID into a string. function Pid (Value : in MAT.Types.Target_Process_Ref) return String; -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format an event range description. function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Tools; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the PID into a string. function Pid (Value : in MAT.Types.Target_Process_Ref) return String; -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the memory growth size into a string. function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format an event range description. function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
Declare the Size function to format a memory growth information (alloced/freed)
Declare the Size function to format a memory growth information (alloced/freed)
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6df7b727a257bd79fcfe100ef4d7a94a652093fc
0060.ads
0060.ads
type errno_t is new int_t; type fcntl_t is new int_t; type whence_t is new int_t; type mntflags_t is new int_t; type amode_t is new uint_t; type ptrace_t is new int_t; type rlimkind_t is new int_t; type rwho_t is new int_t; type mprot_t is new uint_t; type mmap_t is new uint_t; type sysc_t is new int_t; type logopt_t is new uint_t; type logfac_t is new uint_t; type itim_t is new uint_t; type ipccmd_t is new int_t; type short_array is array(Natural range <>) of short_t; type int_array is array(Natural range <>) of int_t; type long_array is array(Natural range <>) of long_t; type llong_array is array(Natural range <>) of llong_t; type ushort_array is array(Natural range <>) of ushort_t; type uint_array is array(Natural range <>) of uint_t; type ulong_array is array(Natural range <>) of ulong_t; type ullong_array is array(Natural range <>) of ullong_t; type DIR is new System.Address; Null_DIR : constant DIR := DIR(System.Null_Address); function "="(L,R : DIR) return Boolean;
type errno_t is new int_t; type fcntl_t is new int_t; type whence_t is new int_t; type mntflags_t is new int_t; type amode_t is new uint_t; type ptrace_t is new int_t; type rlimkind_t is new int_t; type rwho_t is new int_t; type mprot_t is new uint_t; type mmap_t is new uint_t; type sysc_t is new int_t; type logopt_t is new uint_t; type logfac_t is new uint_t; type itim_t is new uint_t; type ipccmd_t is new int_t; type sigpmop_t is new int_t; type short_array is array(Natural range <>) of short_t; type int_array is array(Natural range <>) of int_t; type long_array is array(Natural range <>) of long_t; type llong_array is array(Natural range <>) of llong_t; type ushort_array is array(Natural range <>) of ushort_t; type uint_array is array(Natural range <>) of uint_t; type ulong_array is array(Natural range <>) of ulong_t; type ullong_array is array(Natural range <>) of ullong_t; type DIR is new System.Address; Null_DIR : constant DIR := DIR(System.Null_Address); function "="(L,R : DIR) return Boolean;
Add new type sigpmop_t
Add new type sigpmop_t
Ada
lgpl-2.1
ve3wwg/adafpx,ve3wwg/adafpx
60f6814142117b193ad12cd7d5bf9658bc48dce4
src/gen-commands-propset.adb
src/gen-commands-propset.adb
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Gen.Commands.Propset is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; begin if Args.Get_Count /= 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2)); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUEE"); New_Line; end Help; end Gen.Commands.Propset;
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Gen.Commands.Propset is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); use Ada.Strings.Unbounded; begin if Args.Get_Count /= 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2)); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUEE"); New_Line; end Help; end Gen.Commands.Propset;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
8489f4fec2b0bb5604cf691da358ddf78e8c5da5
awa/plugins/awa-counters/src/awa-counters-beans.adb
awa/plugins/awa-counters/src/awa-counters-beans.adb
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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.Calendar; with Util.Dates.ISO8601; with ADO.Queries.Loaders; with ADO.Sessions.Entities; with AWA.Services.Contexts; package body AWA.Counters.Beans is package ASC renames AWA.Services.Contexts; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Name); begin return Util.Beans.Objects.To_Object (From.Value); end Get_Value; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "stats" then return Util.Beans.Objects.To_Object (Value => List.Stats_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Counters.Models.Stat_List_Bean (List).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if not Util.Beans.Objects.Is_Empty (Value) then AWA.Counters.Models.Stat_List_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Get the query definition to collect the counter statistics. -- ------------------------------ function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access is Name : constant String := Ada.Strings.Unbounded.To_String (From.Query_Name); begin return ADO.Queries.Loaders.Find_Query (Name); end Get_Query; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time is use type Ada.Calendar.Time; Day : Natural; begin if Date'Length = 0 or Date = "now" then return Now; elsif Date'Length > 5 and then Date (Date'First .. Date'First + 3) = "now-" then Day := Natural'Value (Date (Date'First + 4 .. Date'Last)); return Now - Duration (Day * 86400); else return Util.Dates.ISO8601.Value (Date); end if; end Parse_Date; -- ------------------------------ -- Load the statistics information. -- ------------------------------ overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); use type ADO.Identifier; use type ADO.Queries.Query_Definition_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Def : constant ADO.Queries.Query_Definition_Access := List.Get_Query; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (List.Entity_Type); Session : ADO.Sessions.Session := List.Module.Get_Session; Kind : ADO.Entity_Type; First_Date : Ada.Calendar.Time; Last_Date : Ada.Calendar.Time; Query : ADO.Queries.Context; begin Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); First_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.First_Date), Now); Last_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.Last_Date), Now); if List.Entity_Id /= ADO.NO_IDENTIFIER and Def /= null then Query.Set_Query (Def); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", List.Entity_Id); Query.Bind_Param ("user_id", User); Query.Bind_Param ("first_date", First_Date); Query.Bind_Param ("last_date", Last_Date); Query.Bind_Param ("counter_name", List.Counter_Name); AWA.Counters.Models.List (List.Stats, Session, Query); end if; end Load; -- ------------------------------ -- Create the Blog_Stat_Bean bean instance. -- ------------------------------ function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Counter_Stat_Bean_Access := new Counter_Stat_Bean; begin Object.Module := Module; Object.Stats_Bean := Object.Stats'Access; return Object.all'Access; end Create_Counter_Stat_Bean; end AWA.Counters.Beans;
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- Copyright (C) 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Dates.ISO8601; with ADO.Queries.Loaders; with ADO.Sessions.Entities; with AWA.Services.Contexts; package body AWA.Counters.Beans is package ASC renames AWA.Services.Contexts; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Name); begin return Util.Beans.Objects.To_Object (From.Value); end Get_Value; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "stats" then return Util.Beans.Objects.To_Object (Value => List.Stats_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Counters.Models.Stat_List_Bean (List).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if not Util.Beans.Objects.Is_Empty (Value) then AWA.Counters.Models.Stat_List_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Get the query definition to collect the counter statistics. -- ------------------------------ function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access is Name : constant String := Ada.Strings.Unbounded.To_String (From.Query_Name); begin return ADO.Queries.Loaders.Find_Query (Name); end Get_Query; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time is use type Ada.Calendar.Time; Day : Natural; begin if Date'Length = 0 or Date = "now" then return Now; elsif Date'Length > 5 and then Date (Date'First .. Date'First + 3) = "now-" then Day := Natural'Value (Date (Date'First + 4 .. Date'Last)); return Now - Duration (Day * 86400); else return Util.Dates.ISO8601.Value (Date); end if; end Parse_Date; -- ------------------------------ -- Load the statistics information. -- ------------------------------ overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); use type ADO.Identifier; use type ADO.Queries.Query_Definition_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Def : constant ADO.Queries.Query_Definition_Access := List.Get_Query; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (List.Entity_Type); Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Kind : ADO.Entity_Type; First_Date : Ada.Calendar.Time; Last_Date : Ada.Calendar.Time; Query : ADO.Queries.Context; begin Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); First_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.First_Date), Now); Last_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.Last_Date), Now); if List.Entity_Id /= ADO.NO_IDENTIFIER and Def /= null then Query.Set_Query (Def); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", List.Entity_Id); Query.Bind_Param ("user_id", User); Query.Bind_Param ("first_date", First_Date); Query.Bind_Param ("last_date", Last_Date); Query.Bind_Param ("counter_name", List.Counter_Name); AWA.Counters.Models.List (List.Stats, Session, Query); end if; end Load; -- ------------------------------ -- Create the Blog_Stat_Bean bean instance. -- ------------------------------ function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Counter_Stat_Bean_Access := new Counter_Stat_Bean; begin Object.Module := Module; Object.Stats_Bean := Object.Stats'Access; return Object.all'Access; end Create_Counter_Stat_Bean; end AWA.Counters.Beans;
Use the service context to get the database session object
Use the service context to get the database session object
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
acff10c5f48c4a0bf4cc6724ea029a8a2ef7184a
awa/plugins/awa-counters/src/awa-counters.adb
awa/plugins/awa-counters/src/awa-counters.adb
----------------------------------------------------------------------- -- awa-counters -- -- 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 AWA.Counters.Modules; package body AWA.Counters is package body Definition is package Def is new Counter_Arrays.Definition (Table.Table.all); function Kind return Counter_Index_Type is begin return Def.Kind; end Kind; end Definition; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class) is Module : constant AWA.Counters.Modules.Counter_Module_Access := AWA.Counters.Modules.Get_Counter_Module; begin Module.Increment (Counter, Object); end Increment; end AWA.Counters;
----------------------------------------------------------------------- -- awa-counters -- -- 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 AWA.Counters.Modules; package body AWA.Counters is use type Util.Strings.Name_Access; use type ADO.Schemas.Class_Mapping_Access; function "&" (Left : in String; Right : in Counter_Def) return String is begin return Left & "[" & Right.Table.Table.all & ", " & Right.Field.all & "]"; end "&"; function "=" (Left, Right : in Counter_Def) return Boolean is begin return Left.Table = Right.Table and Left.Field = Right.Field; end "="; function "<" (Left, Right : in Counter_Def) return Boolean is begin return Left.Table.Table.all < Right.Table.Table.all or (Left.Table = Right.Table and Left.Field.all < Right.Field.all); end "<"; -- ------------------------------ -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. -- ------------------------------ procedure Increment (Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class) is Module : constant AWA.Counters.Modules.Counter_Module_Access := AWA.Counters.Modules.Get_Counter_Module; begin Module.Increment (Counter, Object); end Increment; end AWA.Counters;
Implement the &, < and = functions for the Counter_Def type
Implement the &, < and = functions for the Counter_Def type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
47351496ba415bcc0d23b0ea9f2075b839523b36
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Time; with ADO; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; New_Content : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Add the New_Comment member in Wiki_Page_Bean type
Add the New_Comment member in Wiki_Page_Bean type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3ffb4fea2b5803e98596abfe4cb8bae6d160ceb2
regtests/asf-rest-tests.ads
regtests/asf-rest-tests.ads
----------------------------------------------------------------------- -- asf-rest-tests - Unit tests for ASF.Rest and ASF.Servlets.Rest -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Rest.Tests is type Test_API is record N : Natural := 0; end record; procedure Create (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Update (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Delete (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure List (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test REST POST create operation procedure Test_Create (T : in out Test); -- Test REST GET operation procedure Test_Get (T : in out Test); -- Test REST PUT update operation procedure Test_Update (T : in out Test); -- Test REST DELETE delete operation procedure Test_Delete (T : in out Test); -- Test REST operation on invalid operation. procedure Test_Invalid (T : in out Test); procedure Test_Operation (T : in out Test; Method : in String; URI : in String; Status : in Natural); end ASF.Rest.Tests;
----------------------------------------------------------------------- -- asf-rest-tests - Unit tests for ASF.Rest and ASF.Servlets.Rest -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Rest.Tests is -- Test API with simple operations. procedure Simple_Get (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Simple_Put (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Simple_Post (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Simple_Delete (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- Test API with an object created for each request. type Test_API is record N : Natural := 0; end record; procedure Create (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Update (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Delete (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure List (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test REST POST create operation procedure Test_Create (T : in out Test); -- Test REST GET operation procedure Test_Get (T : in out Test); -- Test REST PUT update operation procedure Test_Update (T : in out Test); -- Test REST DELETE delete operation procedure Test_Delete (T : in out Test); -- Test REST operation on invalid operation. procedure Test_Invalid (T : in out Test); procedure Test_Operation (T : in out Test; Method : in String; URI : in String; Status : in Natural); end ASF.Rest.Tests;
Declare several REST operations to check the ASF.Rest.Operation package
Declare several REST operations to check the ASF.Rest.Operation package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
45f0e21e93758d357c77843b1081a7c38259699c
mat/src/mat-targets-readers.ads
mat/src/mat-targets-readers.ads
----------------------------------------------------------------------- -- 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 MAT.Events; with MAT.Readers; package MAT.Targets.Readers is type Process_Servant is new MAT.Readers.Reader_Base with record Target : Target_Type_Access; Reader : MAT.Readers.Manager; Process : Target_Process_Type_Access; end record; type Process_Reader_Access is access all Process_Servant'Class; 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); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access); -- 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); 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 MAT.Events; with MAT.Readers; package MAT.Targets.Readers is type Process_Servant is new MAT.Readers.Reader_Base with record Target : Target_Type_Access; Reader : MAT.Readers.Manager; Process : Target_Process_Type_Access; end record; type Process_Reader_Access is access all Process_Servant'Class; -- 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); 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); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access); -- 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); private 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); end MAT.Targets.Readers;
Declare the Create_Process and Probe_Begin operations
Declare the Create_Process and Probe_Begin operations
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9aa0d8a18e5a987deecf867e5ea2dd3b095a60d7
src/gen-model-list.adb
src/gen-model-list.adb
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant EL.Beans.Readonly_Bean_Access := Current.all'Access; begin From.Value_Bean := EL.Objects.To_Object (Bean); end; else From.Value_Bean := EL.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : List_Definition) return EL.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : List_Definition; Name : String) return EL.Objects.Object is pragma Unreferenced (Name); pragma Unreferenced (From); begin return EL.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; end Gen.Model.List;
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant EL.Beans.Readonly_Bean_Access := Current.all'Access; begin From.Value_Bean := EL.Objects.To_Object (Bean); end; else From.Value_Bean := EL.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : List_Definition) return EL.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : List_Definition; Name : String) return EL.Objects.Object is begin if Name = "size" then return EL.Objects.To_Object (From.Get_Count); end if; return EL.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; end Gen.Model.List;
Add a 'size' attribute to value lists
Add a 'size' attribute to value lists
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
d47b71cae2b1d6b3af2e055b8b61b5a23c90f7ca
src/natools-web-exchanges.adb
src/natools-web-exchanges.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Web.Exchanges is procedure Ensure_Kind (Object : in out Exchange; Kind : in Responses.Kind); -- Switch Object.Kind to Kind, resetting internal state if needed ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Ensure_Kind (Object : in out Exchange; Kind : in Responses.Kind) is use type Responses.Kind; begin if Object.Kind /= Kind then Object.Kind := Kind; Object.Response_Body.Soft_Reset; end if; end Ensure_Kind; ----------------------- -- Request Accessors -- ----------------------- function Path (Object : Exchange) return String is begin return AWS.Status.URI (Object.Request.all); end Path; --------------------------- -- Response Construction -- --------------------------- procedure Append (Object : in out Exchange; Data : in S_Expressions.Atom) is begin Ensure_Kind (Object, Responses.Buffer); Object.Response_Body.Append (Data); end Append; procedure Send_File (Object : in out Exchange; File_Name : in S_Expressions.Atom) is begin Ensure_Kind (Object, Responses.File); Object.Response_Body.Soft_Reset; Object.Response_Body.Append (File_Name); end Send_File; --------------------- -- Response Export -- --------------------- function Response (Object : Exchange) return AWS.Response.Data is begin case Object.Kind is when Responses.Empty => raise Program_Error with "Empty response cannot be exported"; when Responses.Buffer => return AWS.Response.Build (S_Expressions.To_String (Object.MIME_Type.Query.Data.all), Object.Response_Body.Data); when Responses.File => return AWS.Response.File (S_Expressions.To_String (Object.MIME_Type.Query.Data.all), S_Expressions.To_String (Object.Response_Body.Data)); end case; end Response; end Natools.Web.Exchanges;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with AWS.MIME; package body Natools.Web.Exchanges is procedure Ensure_Kind (Object : in out Exchange; Kind : in Responses.Kind); -- Switch Object.Kind to Kind, resetting internal state if needed ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Ensure_Kind (Object : in out Exchange; Kind : in Responses.Kind) is use type Responses.Kind; begin if Object.Kind /= Kind then Object.Kind := Kind; Object.Response_Body.Soft_Reset; end if; end Ensure_Kind; ----------------------- -- Request Accessors -- ----------------------- function Path (Object : Exchange) return String is begin return AWS.Status.URI (Object.Request.all); end Path; --------------------------- -- Response Construction -- --------------------------- procedure Append (Object : in out Exchange; Data : in S_Expressions.Atom) is begin Ensure_Kind (Object, Responses.Buffer); Object.Response_Body.Append (Data); end Append; procedure Send_File (Object : in out Exchange; File_Name : in S_Expressions.Atom) is begin Ensure_Kind (Object, Responses.File); Object.Response_Body.Soft_Reset; Object.Response_Body.Append (File_Name); end Send_File; --------------------- -- Response Export -- --------------------- function Response (Object : Exchange) return AWS.Response.Data is begin case Object.Kind is when Responses.Empty => raise Program_Error with "Empty response cannot be exported"; when Responses.Buffer => if Object.MIME_Type.Is_Empty then return AWS.Response.Build ("text/html", Object.Response_Body.Data); else return AWS.Response.Build (S_Expressions.To_String (Object.MIME_Type.Query.Data.all), Object.Response_Body.Data); end if; when Responses.File => if Object.MIME_Type.Is_Empty then declare Filename : constant String := S_Expressions.To_String (Object.Response_Body.Data); begin return AWS.Response.File (AWS.MIME.Content_Type (Filename), Filename); end; else return AWS.Response.File (S_Expressions.To_String (Object.MIME_Type.Query.Data.all), S_Expressions.To_String (Object.Response_Body.Data)); end if; end case; end Response; end Natools.Web.Exchanges;
add default MIME types to response builder
exchanges: add default MIME types to response builder
Ada
isc
faelys/natools-web,faelys/natools-web
6015d09acfd2bafb617c50cb56d8d93bcc87532f
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; 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 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 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; 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 read procedure to read until the end of the stream
Fix read procedure to read until the end of the stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a2c1cfc4d78ad1eb0b8400e5504110599f233843
samples/facebook.adb
samples/facebook.adb
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- Copyright (C) 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Http.Clients.Web; with Util.Http.Rest; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.Web.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User (URI => "https://graph.facebook.com/" & URI, Mapping => Person_Mapping'Unchecked_Access, Into => P'Unchecked_Access); Print (P); end; end loop; end Facebook;
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- Copyright (C) 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Http.Clients.AWS; with Util.Http.Rest; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.AWS.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User (URI => "https://graph.facebook.com/" & URI, Mapping => Person_Mapping'Unchecked_Access, Into => P'Unchecked_Access); Print (P); end; end loop; end Facebook;
Fix compilation of sample
Fix compilation of sample
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
154af01025bd3655256154e7c00100010389a834
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options", Test_Http_Options'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Patch", Test_Http_Patch'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; elsif L (L'First .. Pos - 1) = "OPTIONS" then Into.Method := OPTIONS; elsif L (L'First .. Pos - 1) = "PATCH" then Into.Method := PATCH; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http OPTIONS operation. -- ------------------------------ procedure Test_Http_Options (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Options (Uri & "/options", Reply); T.Assert (T.Server.Method = OPTIONS, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Options; -- ------------------------------ -- Test the http PATCH operation. -- ------------------------------ procedure Test_Http_Patch (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Patch on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Patch (Uri & "/patch", "patch-content", Reply); T.Assert (T.Server.Method = PATCH, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, 200, Reply.Get_Status, "Invalid status response"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); end Test_Http_Patch; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Head", Test_Http_Head'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options", Test_Http_Options'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Patch", Test_Http_Patch'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "HEAD" then Into.Method := HEAD; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; elsif L (L'First .. Pos - 1) = "OPTIONS" then Into.Method := OPTIONS; elsif L (L'First .. Pos - 1) = "PATCH" then Into.Method := PATCH; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http HEAD operation. -- ------------------------------ procedure Test_Http_Head (T : in out Test) is Request : Client; Reply : Response; begin Request.Head ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_head.txt"), Reply, True); T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Head; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http OPTIONS operation. -- ------------------------------ procedure Test_Http_Options (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Options (Uri & "/options", Reply); T.Assert (T.Server.Method = OPTIONS, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Options; -- ------------------------------ -- Test the http PATCH operation. -- ------------------------------ procedure Test_Http_Patch (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Patch on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Patch (Uri & "/patch", "patch-content", Reply); T.Assert (T.Server.Method = PATCH, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, 200, Reply.Get_Status, "Invalid status response"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); end Test_Http_Patch; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
Add the Test_Http_Head and register it for execution
Add the Test_Http_Head and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
57945bab959f9bdeb53b9bd647b6a2aa7d1fdcf4
src/gen-artifacts-query.adb
src/gen-artifacts-query.adb
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Operations; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the method definition in the table -- ------------------------------ procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Operation : Gen.Model.Operations.Operation_Definition_Access; Param : Gen.Model.Operations.Parameter_Definition_Access; begin Table.Add_Operation (Name, Operation); Operation.Add_Parameter (To_Unbounded_String ("Outcome"), To_Unbounded_String ("String"), Param); end Register_Operation; -- ------------------------------ -- Register all the operations defined in the table -- ------------------------------ procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Operation); begin Log.Debug ("Register operations from bean {0}", Table.Name); Iterate (Table, Node, "method"); end Register_Operations; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True); C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", True); C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Query.Is_Serializable := Gen.Utils.Get_Attribute (Node, "serializable", False); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); Register_Operations (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Operations; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the method definition in the table -- ------------------------------ procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Operation : Gen.Model.Operations.Operation_Definition_Access; Param : Gen.Model.Operations.Parameter_Definition_Access; begin Table.Add_Operation (Name, Operation); Operation.Add_Parameter (To_Unbounded_String ("Outcome"), To_Unbounded_String ("String"), Param); end Register_Operation; -- ------------------------------ -- Register all the operations defined in the table -- ------------------------------ procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Operation); begin Log.Debug ("Register operations from bean {0}", Table.Name); Iterate (Table, Node, "method"); end Register_Operations; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True); C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", True); C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Set_Name (Name); else Query.Set_Name (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Query.Is_Serializable := Gen.Utils.Get_Attribute (Node, "serializable", False); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); Register_Operations (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
Update to use Get_Location and Set_Name
Update to use Get_Location and Set_Name
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
bad820e1ab47e9f2ab6fcb5ef2108835617438dd
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 := "00"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "2"; synth_version_minor : constant String := "01"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
Bump version to v2.01
Bump version to v2.01
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
513c7062b835c3d4db51748a95d1343a892d7360
src/asf-views-facelets.ads
src/asf-views-facelets.ads
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Util.Strings.Maps; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.Maps.Map; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Util.Strings.Maps; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.Maps.Map; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
Remove the Path member from the Factelet because this is not used
Remove the Path member from the Factelet because this is not used
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
29caeb37f33d4ef75a6503e7700afc31a1f84ade
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- 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.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; H : Applications.Views.View_Handler; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Resolver : aliased Default_ELResolver; Conf : Applications.Config; Output : ASF.Streams.Print_Stream; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; begin H.Initialize (Conf); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); ELContext.Set_Resolver (Resolver'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", Output); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response)); H.Close; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- 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.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Contexts.Faces; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; App : Applications.Main.Application; Conf : Applications.Config; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin App.Initialize (Conf); App.Dispatch (Page => View_Name, Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Fix the render example to use the ASF Application
Fix the render example to use the ASF Application
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
128ab820a5c2494fe9df443e95eb3b1096674e07
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
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ae6e3833ac8880ab4543bf143be3bdc0bf7ed465
mat/regtests/mat-frames-tests.adb
mat/regtests/mat-frames-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Test_Caller; with MAT.Frames.Print; with MAT.Readers.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Release", Test_Release_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; -- ------------------------------ -- Test allocating and releasing frames. -- ------------------------------ procedure Test_Release_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F1 : Frame_Type; F2 : Frame_Type; F3 : Frame_Type; begin Insert (Root, Frame_1_1, F1); T.Assert (Root.Used > 0, "Insert must increment the root used count"); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_2, F2); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_3, F3); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Output, "Release frame F1"); Release (F1); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); T.Assert (F2.Used > 0, "Release must not change other frames"); T.Assert (Root.Used > 0, "Release must not change root frame"); Destroy (Root); end Test_Release_Frames; end MAT.Frames.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Test_Caller; with MAT.Frames.Print; with MAT.Readers.Streams.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Release", Test_Release_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; -- ------------------------------ -- Test allocating and releasing frames. -- ------------------------------ procedure Test_Release_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F1 : Frame_Type; F2 : Frame_Type; F3 : Frame_Type; begin Insert (Root, Frame_1_1, F1); T.Assert (Root.Used > 0, "Insert must increment the root used count"); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_2, F2); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_3, F3); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Output, "Release frame F1"); Release (F1); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); T.Assert (F2.Used > 0, "Release must not change other frames"); T.Assert (Root.Used > 0, "Release must not change root frame"); Destroy (Root); end Test_Release_Frames; end MAT.Frames.Tests;
Fix compilation of unit test
Fix compilation of unit test
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d112f3a377585b6d4f5ba5770b11683890cd90e4
tools/druss-commands-status.adb
tools/druss-commands-status.adb
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Console.Print_Field (F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.status", " ")); Console.Print_Field (F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Console.Print_Field (F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ENCRYPTION, Gateway.Wifi.Get ("wireless.ssid.24.security.encryption", " ")); Console.End_Row; end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 15); Console.Print_Title (F_WAN_IP, "WAN IP", 15); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Do_Status; -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Do_Status (Args, Context); end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("status: Control and get status about the Bbox Wifi"); Put_Line ("Usage: wifi {<action>} [<parameters>]"); New_Line; Put_Line (" status [IP]... Turn ON the wifi on the Bbox."); Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox."); Put_Line (" wifi show Show information about the wifi on the Bbox."); Put_Line (" wifi devices Show the wifi devices which are connected."); end Help; end Druss.Commands.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.0.address", "x")); Console.End_Row; N := N + 1; Gateway.IPtv.Save_Properties ("iptv" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 15); Console.Print_Title (F_WAN_IP, "WAN IP", 15); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Do_Status; -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Do_Status (Args, Context); end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("status: Control and get status about the Bbox Wifi"); Put_Line ("Usage: wifi {<action>} [<parameters>]"); New_Line; Put_Line (" status [IP]... Turn ON the wifi on the Bbox."); Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox."); Put_Line (" wifi show Show information about the wifi on the Bbox."); Put_Line (" wifi devices Show the wifi devices which are connected."); end Help; end Druss.Commands.Status;
Update the status command to print more information
Update the status command to print more information
Ada
apache-2.0
stcarrez/bbox-ada-api
d5228ff2355e758588209e9c8a435d7d9110f6f9
src/security-auth-oauth.ads
src/security-auth-oauth.ads
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
Add some comment
Add some comment
Ada
apache-2.0
stcarrez/ada-security
60ac1c3bf7d501017a4c29c3a6fa6c8f258d797d
src/util-locales.adb
src/util-locales.adb
----------------------------------------------------------------------- -- Util.Locales -- Locale -- Copyright (C) 2001, 2002, 2003, 2009, 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.Strings.Hash; -- The <b>Locales</b> package defines the <b>Locale</b> type to represent -- the language, country and variant. -- -- The language is a valid <b>ISO language code</b>. This is a two-letter -- lower case code defined by IS-639 -- See http://www.loc.gov/standards/iso639-2/englangn.html -- -- The country is a valid <b>ISO country code</b>. These codes are -- a two letter upper-case code defined by ISO-3166. -- See http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html -- -- The variant part is a vendor or browser specific code. -- -- The <b>Locales</b> package tries to follow the Java <b>Locale</b> class. package body Util.Locales is -- ------------------------------ -- Get the lowercase two-letter ISO-639 code. -- ------------------------------ function Get_Language (Loc : in Locale) return String is begin if Loc = null then return ""; else return Loc (1 .. 2); end if; end Get_Language; -- ------------------------------ -- Get the ISO 639-2 language code. -- ------------------------------ function Get_ISO3_Language (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 3 then return ""; end if; if Loc'Length <= 6 then return Loc (4 .. 6); end if; return Loc (7 .. 9); end Get_ISO3_Language; -- ------------------------------ -- Get the uppercase two-letter ISO-3166 code. -- ------------------------------ function Get_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then return ""; else return Loc (4 .. 5); end if; end Get_Country; -- ------------------------------ -- Get the ISO-3166-2 country code. -- ------------------------------ function Get_ISO3_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 5 then return ""; else return Loc (10 .. Loc'Last); end if; end Get_ISO3_Country; -- ------------------------------ -- Get the variant code -- ------------------------------ function Get_Variant (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 13 then return ""; else return Loc (7 .. 8); end if; end Get_Variant; -- ------------------------------ -- Get the locale for the given language code -- ------------------------------ function Get_Locale (Language : in String) return Locale is Length : constant Natural := Language'Length; Lower : Natural := Locales'First; Upper : Natural := Locales'Last; Pos : Natural; Result : Locale; begin while Lower <= Upper loop Pos := (Lower + Upper) / 2; Result := Locales (Pos); if Result'Length < Length then if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then Lower := Pos + 1; else Upper := Pos - 1; end if; elsif Result'Length > Length and then Result (Length + 1) = '.' and then Result (1 .. Length) = Language then return Result; elsif Result (1 .. Length) < Language then Lower := Pos + 1; else Upper := Pos - 1; end if; end loop; return NULL_LOCALE; end Get_Locale; -- ------------------------------ -- Get the locale for the given language and country code -- ------------------------------ function Get_Locale (Language : in String; Country : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then return NULL_LOCALE; elsif Country'Length = 0 then return Get_Locale (Language); else return Get_Locale (Language & "_" & Country); end if; end Get_Locale; -- ------------------------------ -- Get the locale for the given language, country and variant code -- ------------------------------ function Get_Locale (Language : in String; Country : in String; Variant : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) or else (Variant'Length /= 0 and Variant'Length /= 2) then return NULL_LOCALE; end if; if Country'Length = 0 and Variant'Length = 0 then return Get_Locale (Language); elsif Variant'Length = 0 then return Get_Locale (Language, Country); else return Get_Locale (Language & "_" & Country & "_" & Variant); end if; end Get_Locale; -- ------------------------------ -- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>. -- ------------------------------ function To_String (Loc : in Locale) return String is begin if Loc = null then return ""; elsif Loc'Length > 3 and Loc (3) = '.' then return Loc (1 .. 2); elsif Loc'Length > 6 and Loc (6) = '.' then return Loc (1 .. 5); else return Loc (1 .. 8); end if; end To_String; -- ------------------------------ -- Compute the hash value of the locale. -- ------------------------------ function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is use type Ada.Containers.Hash_Type; begin return Ada.Strings.Hash (Loc.all); end Hash; end Util.Locales;
----------------------------------------------------------------------- -- util-locales -- Locale support -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; package body Util.Locales is -- ------------------------------ -- Get the lowercase two-letter ISO-639 code. -- ------------------------------ function Get_Language (Loc : in Locale) return String is begin if Loc = null then return ""; else return Loc (1 .. 2); end if; end Get_Language; -- ------------------------------ -- Get the ISO 639-2 language code. -- ------------------------------ function Get_ISO3_Language (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 3 then return ""; end if; if Loc'Length <= 6 then return Loc (4 .. 6); end if; return Loc (7 .. 9); end Get_ISO3_Language; -- ------------------------------ -- Get the uppercase two-letter ISO-3166 code. -- ------------------------------ function Get_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then return ""; else return Loc (4 .. 5); end if; end Get_Country; -- ------------------------------ -- Get the ISO-3166-2 country code. -- ------------------------------ function Get_ISO3_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 5 then return ""; else return Loc (10 .. Loc'Last); end if; end Get_ISO3_Country; -- ------------------------------ -- Get the variant code -- ------------------------------ function Get_Variant (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 13 then return ""; else return Loc (7 .. 8); end if; end Get_Variant; -- ------------------------------ -- Get the locale for the given language code -- ------------------------------ function Get_Locale (Language : in String) return Locale is Length : constant Natural := Language'Length; Lower : Natural := Locales'First; Upper : Natural := Locales'Last; Pos : Natural; Result : Locale; begin while Lower <= Upper loop Pos := (Lower + Upper) / 2; Result := Locales (Pos); if Result'Length < Length then if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then Lower := Pos + 1; else Upper := Pos - 1; end if; elsif Result'Length > Length and then Result (Length + 1) = '.' and then Result (1 .. Length) = Language then return Result; elsif Result (1 .. Length) < Language then Lower := Pos + 1; else Upper := Pos - 1; end if; end loop; return NULL_LOCALE; end Get_Locale; -- ------------------------------ -- Get the locale for the given language and country code -- ------------------------------ function Get_Locale (Language : in String; Country : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then return NULL_LOCALE; elsif Country'Length = 0 then return Get_Locale (Language); else return Get_Locale (Language & "_" & Country); end if; end Get_Locale; -- ------------------------------ -- Get the locale for the given language, country and variant code -- ------------------------------ function Get_Locale (Language : in String; Country : in String; Variant : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) or else (Variant'Length /= 0 and Variant'Length /= 2) then return NULL_LOCALE; end if; if Country'Length = 0 and Variant'Length = 0 then return Get_Locale (Language); elsif Variant'Length = 0 then return Get_Locale (Language, Country); else return Get_Locale (Language & "_" & Country & "_" & Variant); end if; end Get_Locale; -- ------------------------------ -- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>. -- ------------------------------ function To_String (Loc : in Locale) return String is begin if Loc = null then return ""; elsif Loc'Length > 3 and Loc (3) = '.' then return Loc (1 .. 2); elsif Loc'Length > 6 and Loc (6) = '.' then return Loc (1 .. 5); else return Loc (1 .. 8); end if; end To_String; -- ------------------------------ -- Compute the hash value of the locale. -- ------------------------------ function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is use type Ada.Containers.Hash_Type; begin return Ada.Strings.Hash (Loc.all); end Hash; end Util.Locales;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
614f75c5eb70a5934233385ed8c6a2d18f06e18a
src/util-serialize-io.adb
src/util-serialize-io.adb
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 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 Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Push the current context when entering in an element. -- ------------------------------ procedure Push (Handler : in out Parser) is use type Util.Serialize.Mappers.Mapper_Access; begin Context_Stack.Push (Handler.Stack); end Push; -- ------------------------------ -- Pop the context and restore the previous context when leaving an element -- ------------------------------ procedure Pop (Handler : in out Parser) is begin Context_Stack.Pop (Handler.Stack); end Pop; function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access is pragma Unreferenced (Handler, Name); begin return null; end Find_Mapper; -- ------------------------------ -- 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. -- ------------------------------ procedure Start_Object (Handler : in out Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); Next : Element_Context_Access; Pos : Positive; begin Log.Debug ("Start object {0}", Name); Context_Stack.Push (Handler.Stack); Next := Context_Stack.Current (Handler.Stack); if Current /= null then Pos := 1; -- Notify we are entering in the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); Child : Mappers.Mapper_Access; begin exit when Node = null; Child := Node.Find_Mapper (Name => Name); if Child = null and then Node.Is_Wildcard then Child := Node; end if; if Child /= null then Log.Debug ("{0} is matching {1}", Name, Child.Get_Name); Child.Start_Object (Handler, Name); Next.Active_Nodes (Pos) := Child; Pos := Pos + 1; end if; end; end loop; while Pos <= Next.Active_Nodes'Last loop Next.Active_Nodes (Pos) := null; Pos := Pos + 1; end loop; else Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name); 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. -- ------------------------------ procedure Finish_Object (Handler : in out Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; begin Log.Debug ("Finish object {0}", Name); declare Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin if Current /= null then -- Notify we are leaving the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Finish_Object (Handler, Name); end; end loop; end if; end; Handler.Pop; end Finish_Object; procedure Start_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Push; end Start_Array; procedure Finish_Array (Handler : in out Parser; Name : in String; Count : in Natural) is pragma Unreferenced (Name, Count); begin Handler.Pop; 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. -- ----------------------- procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is use Util.Serialize.Mappers; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin Log.Debug ("Set member {0}", Name); if Current /= null then -- Look each active mapping node. for I in Current.Active_Nodes'Range loop declare Node : constant Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Set_Member (Name => Name, Value => Value, Attribute => Attribute, Context => Handler); exception when E : Util.Serialize.Mappers.Field_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); when E : Util.Serialize.Mappers.Field_Fatal_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); raise; -- For other exception, report an error with the field name and value. when E : others => Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '" & Util.Beans.Objects.To_String (Value) & "': " & Ada.Exceptions.Exception_Message (E)); raise; end; end loop; end if; end Set_Member; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Handler.Mapping_Tree.Add_Mapping (Path, Mapper); end Add_Mapping; -- ------------------------------ -- Dump the mapping tree on the logger using the INFO log level. -- ------------------------------ procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class) is begin Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping "); end Dump; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 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 Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); -- Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); -- Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; end Util.Serialize.IO;
Move the Start_Object, Finish_Object, Start_Array, End_Array, Push Pop, Set_Member operations to the Mappers package Use the Reader interface object
Move the Start_Object, Finish_Object, Start_Array, End_Array, Push Pop, Set_Member operations to the Mappers package Use the Reader interface object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a81846ab1effd1fd676f755ac2a766f8b02cb698
src/wiki-nodes.adb
src/wiki-nodes.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. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Block.Max * 2); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then Finalize (Block.List (I).Children.all); Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 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.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Block.Max * 2); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then Finalize (Block.List (I).Children.all); Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; end Wiki.Nodes;
Refactor Node_List and references to use Ada Util general references
Refactor Node_List and references to use Ada Util general references
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
89b3f5ecb96104fddd61e870ced1218c41254746
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Ada.Finalization; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : WString (1 .. Len); when others => null; end case; end record; type Document is tagged private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- 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); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- 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_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- 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 (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- 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)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); subtype Node_List_Ref is Node_List_Refs.Ref; type Document is new Ada.Finalization.Controlled with record Nodes : Node_List_Ref; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Ada.Finalization; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : WString (1 .. Len); when others => null; end case; end record; type Document is tagged private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- 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); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- 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_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- 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 (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- 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)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); subtype Node_List_Ref is Node_List_Refs.Ref; type Document is new Ada.Finalization.Controlled with record Nodes : Node_List_Ref; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); end Wiki.Nodes;
Add N_LIST and N_NUM_LIST types
Add N_LIST and N_NUM_LIST types
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d1c8ca65139b3fde5f3179ae8e70d84fcf639bd2
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String is begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Set_Reader_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is -- Policy_Mapping : aliased Policy_Mapper.Mapper; Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Set_Reader_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is -- Policy_Mapping : aliased Policy_Mapper.Mapper; Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
Letractively/ada-security
be813acd48e3fa01ff8c89e22fd88b2dd82a9677
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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 System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; use type Interfaces.Unsigned_16; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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 Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; use type Interfaces.Unsigned_16; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Uint32); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; function Get_Target_Process_Ref (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Process_Ref is function Get_Value is new Get_Target_Value (MAT.Types.Target_Process_Ref); begin return Get_Value (Msg, Kind); end Get_Target_Process_Ref; end MAT.Readers.Marshaller;
Implement Get_Target_Process_Ref function
Implement Get_Target_Process_Ref function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
89f8f26a3297fcc28a6a0933a5f4101deef8838b
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is Ctx : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin return EL.Expressions.Create_Expression (Value, Ctx); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Ctx); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Implement the Get_Config procedure that parses and returns an EL expression
Implement the Get_Config procedure that parses and returns an EL expression
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d0bbc6691b213ff11b36fa7a9910dec18f44672e
src/wiki-helpers-parser.adb
src/wiki-helpers-parser.adb
----------------------------------------------------------------------- -- wiki-helpers-parser -- Generic procedure for the wiki parser -- Copyright (C) 2016, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Streams; procedure Wiki.Helpers.Parser (Engine : in out Engine_Type; Content : in Element_Type; Doc : in out Wiki.Documents.Document) is type Wide_Input is new Wiki.Streams.Input_Stream with record Pos : Positive; Len : Natural; end record; -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. overriding procedure Read (Input : in out Wide_Input; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean); overriding procedure Read (Input : in out Wide_Input; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean) is Pos : Natural := Into'First; Char : Wiki.Strings.WChar; begin Eof := False; while Pos <= Into'Last loop if Input.Pos <= Input.Len then Element (Content, Input.Pos, Char); else Eof := True; exit; end if; Into (Pos) := Char; Pos := Pos + 1; exit when Char = Helpers.CR or Char = Helpers.LF; end loop; Last := Pos - 1; 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, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Streams; procedure Wiki.Helpers.Parser (Engine : in out Engine_Type; Content : in Element_Type; Doc : in out Wiki.Documents.Document) is type Wide_Input is new Wiki.Streams.Input_Stream with record Pos : Positive; Len : Natural; end record; -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. overriding procedure Read (Input : in out Wide_Input; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean); overriding procedure Read (Input : in out Wide_Input; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean) is Pos : Natural := Into'First; Char : Wiki.Strings.WChar; begin Eof := False; while Pos <= Into'Last loop if Input.Pos <= Input.Len then Element (Content, Input.Pos, Char); else Eof := True; exit; end if; Into (Pos) := Char; Pos := Pos + 1; exit when Char = Helpers.LF; if Char = Helpers.CR then exit when Input.Pos > Input.Len; -- Look for a possible LF and drop it. declare Read_Pos : constant Natural := Input.Pos; begin Element (Content, Input.Pos, Char); if Char /= Helpers.LF then Input.Pos := Read_Pos; end if; exit; end; end if; end loop; Last := Pos - 1; end Read; Buffer : aliased Wide_Input; begin Buffer.Pos := 1; Buffer.Len := Length (Content); Parse (Engine, Buffer'Unchecked_Access, Doc); end Wiki.Helpers.Parser;
Fix handling CR LF sequences when reading a line
Fix handling CR LF sequences when reading a line
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2ef1bf203951d80012ea9cf0095b33b062fb894e
src/ado-utils.ads
src/ado-utils.ads
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; package ADO.Utils is -- Build a bean object from the identifier. function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object; -- Build the identifier from the bean object. function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier; -- Compute the hash of the identifier. function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type; package Identifier_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => ADO.Identifier, "=" => "="); subtype Identifier_Vector is Identifier_Vectors.Vector; subtype Identifier_Cursor is Identifier_Vectors.Cursor; -- Return the identifier list as a comma separated list of identifiers. function To_Parameter_List (List : in Identifier_Vector) return String; end ADO.Utils;
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; with Util.Serialize.IO; package ADO.Utils is -- Build a bean object from the identifier. function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object; -- Build the identifier from the bean object. function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier; -- Compute the hash of the identifier. function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type; package Identifier_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => ADO.Identifier, "=" => "="); subtype Identifier_Vector is Identifier_Vectors.Vector; subtype Identifier_Cursor is Identifier_Vectors.Cursor; -- Return the identifier list as a comma separated list of identifiers. function To_Parameter_List (List : in Identifier_Vector) return String; -- Write the entity to the serialization stream (JSON/XML). procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Value : in ADO.Identifier); end ADO.Utils;
Declare the Write_Entity operation to write a ADO.Identifier type on a JSON/XML stream
Declare the Write_Entity operation to write a ADO.Identifier type on a JSON/XML stream
Ada
apache-2.0
stcarrez/ada-ado
65d950d7855549695354e908030d78b0a50eef7f
awa/plugins/awa-images/src/awa-images-services.adb
awa/plugins/awa-images/src/awa-images-services.adb
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; Name : Ada.Strings.Unbounded.Unbounded_String; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Services;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
29b7d5af6545a0aba995e3a7033afb378a78cc24
awa/plugins/awa-sysadmin/src/awa-sysadmin-modules.adb
awa/plugins/awa-sysadmin/src/awa-sysadmin-modules.adb
----------------------------------------------------------------------- -- awa-sysadmin-modules -- Module sysadmin -- Copyright (C) 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 AWA.Applications; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Sysadmin.Models; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements; with ADO.Queries; with ADO.Utils.Serialize; with Servlet.Rest; with Swagger.Servers.Operation; with AWA.Sysadmin.Beans; package body AWA.Sysadmin.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module"); package Register is new AWA.Modules.Beans (Module => Sysadmin_Module, Module_Access => Sysadmin_Module_Access); Mimes : aliased constant Swagger.Servers.Mime_List := (1 => Swagger.Servers.Mime_Json, 2 => Swagger.Servers.Mime_Xml); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); package API_List_Users is new Swagger.Servers.Operation (Handler => List_Users, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/users", Mimes => Mimes'Access); package API_List_Sessions is new Swagger.Servers.Operation (Handler => List_Sessions, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/sessions", Mimes => Mimes'Access); package API_List_Jobs is new Swagger.Servers.Operation (Handler => List_Jobs, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/jobs", Mimes => Mimes'Access); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List users"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Users; procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List sessions"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Session_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Sessions; procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List jobs"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Job_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Jobs; -- ------------------------------ -- Initialize the sysadmin module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Sysadmin_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the sysadmin module"); App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access); App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access); Register.Register (Plugin => Plugin, Name => "AWA.Sysadmin.Beans.Authenticate_Bean", Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access); App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*"); AWA.Modules.Module (Plugin).Initialize (App, Props); Servlet.Rest.Register (App.all, API_List_Users.Definition); Servlet.Rest.Register (App.all, API_List_Sessions.Definition); Servlet.Rest.Register (App.all, API_List_Jobs.Definition); end Initialize; -- ------------------------------ -- Get the sysadmin module. -- ------------------------------ function Get_Sysadmin_Module return Sysadmin_Module_Access is function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME); begin return Get; end Get_Sysadmin_Module; end AWA.Sysadmin.Modules;
----------------------------------------------------------------------- -- awa-sysadmin-modules -- Module sysadmin -- Copyright (C) 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 AWA.Applications; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Sysadmin.Models; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements; with ADO.Queries; with ADO.Utils.Serialize; with Servlet.Rest; with Swagger.Servers.Operation; with AWA.Sysadmin.Beans; package body AWA.Sysadmin.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module"); package Register is new AWA.Modules.Beans (Module => Sysadmin_Module, Module_Access => Sysadmin_Module_Access); Mimes : aliased constant Swagger.Mime_List := (1 => Swagger.Mime_Json, 2 => Swagger.Mime_Xml); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); package API_List_Users is new Swagger.Servers.Operation (Handler => List_Users, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/users", Mimes => Mimes'Access); package API_List_Sessions is new Swagger.Servers.Operation (Handler => List_Sessions, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/sessions", Mimes => Mimes'Access); package API_List_Jobs is new Swagger.Servers.Operation (Handler => List_Jobs, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/jobs", Mimes => Mimes'Access); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List users"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Users; procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List sessions"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Session_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Sessions; procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List jobs"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Job_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Jobs; -- ------------------------------ -- Initialize the sysadmin module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Sysadmin_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the sysadmin module"); App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access); App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access); Register.Register (Plugin => Plugin, Name => "AWA.Sysadmin.Beans.Authenticate_Bean", Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access); App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*"); AWA.Modules.Module (Plugin).Initialize (App, Props); Servlet.Rest.Register (App.all, API_List_Users.Definition); Servlet.Rest.Register (App.all, API_List_Sessions.Definition); Servlet.Rest.Register (App.all, API_List_Jobs.Definition); end Initialize; -- ------------------------------ -- Get the sysadmin module. -- ------------------------------ function Get_Sysadmin_Module return Sysadmin_Module_Access is function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME); begin return Get; end Get_Sysadmin_Module; end AWA.Sysadmin.Modules;
Update for OpenAPI
Update for OpenAPI
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8ea85b1356d5b604326b2fb2ad87af8728826ecf
awa/plugins/awa-jobs/src/awa-jobs-services.adb
awa/plugins/awa-jobs/src/awa-jobs-services.adb
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012, 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.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with ADO.Statements; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type is Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : constant ADO.Sessions.Session := ASC.Get_Session (Ctx); Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT status FROM awa_job WHERE id = ?"); begin Stmt.Add_Param (Id); Stmt.Execute; return Models.Job_Status_Type'Val (Stmt.Get_Result_Integer); end Get_Job_Status; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Set the job result identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Results.Include (Name, Value); Job.Results_Modified := True; end Set_Result; -- ------------------------------ -- Set the job result identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Result (Name, Util.Beans.Objects.To_Object (Value)); end Set_Result; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. -- ------------------------------ function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier is begin return Job.Job.Get_Id; end Get_Identifier; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => Log.Info ("Job {0} is closed", ADO.Identifier'Image (Job.Job.Get_Id)); raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Props_Modified then Job.Job.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); Job.Props_Modified := False; end if; if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. Log.Info ("Execute job {0}", String '(Job.Job.Get_Name)); begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; Id : constant ADO.Identifier := Event.Get_Entity_Identifier; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Id); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; Ident : constant String := ADO.Identifier'Image (Id); begin Log.Info ("Restoring job {0} - '{1}'", Ident, Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Event.Copy (Work.Props); Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job {0} - '{1}'", Ident, Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; -- ------------------------------ -- Get the job factory name. -- ------------------------------ function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; -- ------------------------------ -- Create the job instance to execute the associated <tt>Work_Access</tt> procedure. -- ------------------------------ overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012, 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.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with ADO.Statements; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type is Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : constant ADO.Sessions.Session := ASC.Get_Session (Ctx); Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT status FROM awa_job WHERE id = ?"); begin Stmt.Add_Param (Id); Stmt.Execute; return Models.Job_Status_Type'Val (Stmt.Get_Result_Integer); end Get_Job_Status; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in ADO.Objects.Object_Ref'Class) is begin if Value.Is_Null then Job.Set_Parameter (Name, Util.Beans.Objects.Null_Object); else Job.Set_Parameter (Name, ADO.Objects.To_Object (Value.Get_Key)); end if; end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Set the job result identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Results.Include (Name, Value); Job.Results_Modified := True; end Set_Result; -- ------------------------------ -- Set the job result identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Result (Name, Util.Beans.Objects.To_Object (Value)); end Set_Result; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. -- ------------------------------ function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier is begin return Job.Job.Get_Id; end Get_Identifier; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => Log.Info ("Job {0} is closed", ADO.Identifier'Image (Job.Job.Get_Id)); raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Props_Modified then Job.Job.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); Job.Props_Modified := False; end if; if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. Log.Info ("Execute job {0}", String '(Job.Job.Get_Name)); begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; Id : constant ADO.Identifier := Event.Get_Entity_Identifier; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Id); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; Ident : constant String := ADO.Identifier'Image (Id); begin Log.Info ("Restoring job {0} - '{1}'", Ident, Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Event.Copy (Work.Props); Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job {0} - '{1}'", Ident, Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; -- ------------------------------ -- Get the job factory name. -- ------------------------------ function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; -- ------------------------------ -- Create the job instance to execute the associated <tt>Work_Access</tt> procedure. -- ------------------------------ overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
Implement the new Set_Parameter procedure
Implement the new Set_Parameter procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
14cb1c7a41dd27d2f75be3735dea477b58ac77b6
awa/src/awa-blogs-beans.adb
awa/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; function Get_Parameter (Name : in String) return ADO.Identifier; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; function Get_Parameter (Name : in String) return ADO.Identifier; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is use type ASF.Contexts.Faces.Faces_Context_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Ctx = null then return ADO.NO_IDENTIFIER; else declare P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; end; end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
Check that the faces context is defined before getting parameters
Check that the faces context is defined before getting parameters
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
7516b4c4138a7d3b89472b665144e0091ae0e397
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Implement the protected operation Add_Region
Implement the protected operation Add_Region
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c74fb1cf67f5dbb29e4807ab1a457a63df7e792b
regtests/util-files-tests.ads
regtests/util-files-tests.ads
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); procedure Test_Read_File_Missing (T : in out Test); procedure Test_Read_File_Truncate (T : in out Test); procedure Test_Write_File (T : in out Test); procedure Test_Find_File_Path (T : in out Test); procedure Test_Iterate_Path (T : in out Test); procedure Test_Compose_Path (T : in out Test); -- Test the Get_Relative_Path operation. procedure Test_Get_Relative_Path (T : in out Test); end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); procedure Test_Read_File_Missing (T : in out Test); procedure Test_Read_File_Truncate (T : in out Test); procedure Test_Write_File (T : in out Test); procedure Test_Find_File_Path (T : in out Test); procedure Test_Iterate_Path (T : in out Test); procedure Test_Compose_Path (T : in out Test); -- Test the Get_Relative_Path operation. procedure Test_Get_Relative_Path (T : in out Test); -- Test the Delete_Tree operation. procedure Test_Delete_Tree (T : in out Test); end Util.Files.Tests;
Declare the Test_Delete_Tree procedure
Declare the Test_Delete_Tree procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1d6bbeadcb9f679e8e9a2fda899d8045d57693a8
src/os-linux/util-processes-os.ads
src/os-linux/util-processes-os.ads
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; with Interfaces.C.Strings; private package Util.Processes.Os is type System_Process is new Util.Processes.System_Process with record Argv : Util.Systems.Os.Ptr_Ptr_Array := null; Argc : Interfaces.C.Size_T := 0; In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_Append : Boolean := False; Err_Append : Boolean := False; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Systems.Os.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; with Interfaces.C.Strings; private package Util.Processes.Os is type System_Process is new Util.Processes.System_Process with record Argv : Util.Systems.Os.Ptr_Ptr_Array := null; Argc : Interfaces.C.size_t := 0; In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_Append : Boolean := False; Err_Append : Boolean := False; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Systems.Os.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
Fix style in size_t identifier
Fix style in size_t identifier
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
da83c4c19cf48ac7bd440758989b0af693f910b6
regtests/ado-statements-tests.adb
regtests/ado-statements-tests.adb
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); if Stmt.Is_Null (0) then return 0; else return Stmt.Get_Integer (0); end if; end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); if Stmt.Is_Null (0) then return 0; else return Stmt.Get_Integer (0); end if; end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer (raise Invalid_Column)", Test_Invalid_Column'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); if Stmt.Is_Null (0) then return 0; else return Stmt.Get_Integer (0); end if; end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); if Stmt.Is_Null (0) then return 0; else return Stmt.Get_Integer (0); end if; end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; -- ------------------------------ -- Test executing a SQL query and getting an invalid column. -- ------------------------------ procedure Test_Invalid_Column (T : in out Test) is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; Name : Ada.Strings.Unbounded.Unbounded_String; Value : Integer := 123456789; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type"); Stmt.Execute; while Stmt.Has_Elements loop Name := Stmt.Get_Unbounded_String (0); T.Assert (Ada.Strings.Unbounded.Length (Name) > 0, "Invalid entity_type name"); begin Value := Stmt.Get_Integer (1); Util.Tests.Fail (T, "No exception raised for Stmt.Get_Integer"); exception when ADO.Statements.Invalid_Column => null; end; begin Name := Stmt.Get_Unbounded_String (1); Util.Tests.Fail (T, "No exception raised for Stmt.Get_Unbounded_String"); exception when ADO.Statements.Invalid_Column => null; end; begin T.Assert (Stmt.Get_Boolean (1), "Get_Boolean"); Util.Tests.Fail (T, "No exception raised for Stmt.Get_Unbounded_String"); exception when ADO.Statements.Invalid_Column => null; end; Util.Tests.Assert_Equals (T, 123456789, Value, "Value was corrupted"); Count := Count + 1; Stmt.Next; end loop; T.Assert (Count > 0, "Query must return at least on entity_type"); end Test_Invalid_Column; end ADO.Statements.Tests;
Implement the Test_Invalid_Column procedure to verify the Invalid_Column exception is raised correctly
Implement the Test_Invalid_Column procedure to verify the Invalid_Column exception is raised correctly
Ada
apache-2.0
stcarrez/ada-ado
edcba4e6e0850e57996521ac81a4527246795a39
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table_Ptr); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Attribute_Table_Ptr; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message -- procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
Fix the Message_Handler and Register_Reader to use a constant attribute definition table
Fix the Message_Handler and Register_Reader to use a constant attribute definition table
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b6c782dd1fcfc22a53421ebe40aa0f8db264694d
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Wikis.Servlets; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; with Wiki.Strings; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- The configuration parameter that defines the page link prefix in rendered HTML content. PARAM_PAGE_PREFIX : constant String := "page_prefix"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Wiki_Module; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the page prefix that was configured for the Wiki module. function Get_Page_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); procedure Load_Image (Model : in Wiki_Module; Wiki_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Wikis.Servlets.Image_Servlet; Page_Prefix : Wiki.Strings.UString; end record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- 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.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Wikis.Servlets; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; with Wiki.Strings; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- The configuration parameter that defines the page link prefix in rendered HTML content. PARAM_PAGE_PREFIX : constant String := "page_prefix"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Wiki_Module; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the page prefix that was configured for the Wiki module. function Get_Page_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); procedure Load_Image (Model : in Wiki_Module; Wiki_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Wikis.Servlets.Image_Servlet; Page_Prefix : Wiki.Strings.UString; end record; end AWA.Wikis.Modules;
Change Load_Image to have a Width and Height parameter
Change Load_Image to have a Width and Height parameter
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7379ffeb9e3575083e042bcaa1b2662afc3d0909
regtests/security-auth-tests.adb
regtests/security-auth-tests.adb
----------------------------------------------------------------------- -- security-auth-tests - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Setup (M : in out Manager; Name : in String); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); pragma Style_Checks ("-mr"); -- M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Util.Tests.Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
----------------------------------------------------------------------- -- security-auth-tests - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Setup (M : in out Manager; Name : in String); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); pragma Style_Checks ("-mr"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Util.Tests.Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
Remove unecessary comment
Remove unecessary comment
Ada
apache-2.0
stcarrez/ada-security
c093a765fce15db0b7ec0ef1f73832857f5f8ffd
samples/api_server.adb
samples/api_server.adb
----------------------------------------------------------------------- -- api_server -- Example of REST API server -- 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 ASF.Server.Web; with ASF.Servlets.Rest; with ASF.Servlets.Files; with ASF.Applications; with Util.Log.Loggers; with Monitor; with EL.Contexts.Default; procedure API_Server is CONFIG_PATH : constant String := "samples.properties"; Api : aliased ASF.Servlets.Rest.Rest_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; Ctx : EL.Contexts.Default.Default_Context; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Api_Server"); begin Util.Log.Loggers.Initialize (CONFIG_PATH); App.Set_Init_Parameter (ASF.Applications.VIEW_DIR, "samples/web/monitor"); -- Register the servlets and filters App.Add_Servlet (Name => "api", Server => Api'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "api", Pattern => "/api/*"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); Monitor.Mon_API.Register (App, "api", Ctx); WS.Register_Application ("/monitor", App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/monitor/index.html"); WS.Start; delay 6000.0; end API_Server;
----------------------------------------------------------------------- -- api_server -- Example of REST API server -- 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 ASF.Server.Web; with ASF.Servlets.Rest; with ASF.Servlets.Files; with ASF.Applications; with ASF.Rest; with Util.Log.Loggers; with Monitor; with EL.Contexts.Default; procedure API_Server is CONFIG_PATH : constant String := "samples.properties"; Api : aliased ASF.Servlets.Rest.Rest_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; Ctx : EL.Contexts.Default.Default_Context; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Api_Server"); begin Util.Log.Loggers.Initialize (CONFIG_PATH); App.Set_Init_Parameter (ASF.Applications.VIEW_DIR, "samples/web/monitor"); -- Register the servlets and filters App.Add_Servlet (Name => "api", Server => Api'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "api", Pattern => "/api/*"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); -- Monitor.Mon_API.Register (App, "api", Ctx); ASF.Rest.Register (App, Monitor.API_Get_Values.Definition); ASF.Rest.Register (App, Monitor.API_Put_Value.Definition); WS.Register_Application ("/monitor", App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/monitor/index.html"); WS.Start; delay 6000.0; end API_Server;
Update the REST API server example
Update the REST API server example
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8ebffc9b36920f09d36d28e5f109d48fe39e3858
src/util-commands-drivers.adb
src/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then -- Usage; New_Line; Put ("Type '"); -- Put (Ada.Command_Line.Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then -- Usage; New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Implement the Set_Description procedure
Implement the Set_Description procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
725ebb57bd56b2ce318ccabc50ce51fdebe50207
matp/src/mat-targets-probes.adb
matp/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; Region.Path := Path; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Load the symbols when we recieve and insert the new memory region
Load the symbols when we recieve and insert the new memory region
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f7b71d45506567a659611232e5cf4ae9bc682f95
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the tests for the AWA.Changelogs plugin
Add the tests for the AWA.Changelogs plugin
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
190532c3a6af490e98a8e5866ff6587a7890f479
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the wiki module tests
Add the wiki module tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
75cf739b97a3d61eef1b5f7cdf696a9f9fca5d2c
awa/src/awa-commands-start.adb
awa/src/awa-commands-start.adb
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Servlet.Core; with Servlet.Server; with GNAT.Sockets; with AWA.Applications; package body AWA.Commands.Start is use Ada.Strings.Unbounded; use GNAT.Sockets; use type System.Address; -- ------------------------------ -- Start the server and all the application that have been registered. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Configure_Server (Context); Command.Configure_Applications (Context); Command.Start_Server (Context); Command.Wait_Server (Context); end Execute; -- ------------------------------ -- Configure the web server container before applications are registered. -- ------------------------------ procedure Configure_Server (Command : in out Command_Type; Context : in out Context_Type) is Config : Servlet.Server.Configuration; begin -- If daemon(3) is available and -d is defined, run it so that the parent -- process terminates and the child process continues. if Command.Daemon and Sys_Daemon'Address /= System.Null_Address then declare Result : constant Integer := Sys_Daemon (1, 0); begin if Result /= 0 then Context.Console.Error ("Cannot run in background"); end if; end; end if; Config.Listening_Port := Command.Listening_Port; Config.Max_Connection := Command.Max_Connection; Config.TCP_No_Delay := Command.TCP_No_Delay; if Command.Upload'Length > 0 then Config.Upload_Directory := To_Unbounded_String (Command.Upload.all); end if; Command_Drivers.WS.Configure (Config); end Configure_Server; -- ------------------------------ -- Configure all registered applications. -- ------------------------------ procedure Configure_Applications (Command : in out Command_Type; Context : in out Context_Type) is procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then Configure (AWA.Applications.Application'Class (Application.all), URI (URI'First + 1 .. URI'Last), Context); Count := Count + 1; end if; end Configure; Config : Servlet.Server.Configuration; begin Command_Drivers.WS.Iterate (Configure'Access); if Count = 0 then Context.Console.Error (-("There is no application")); return; end if; end Configure_Applications; -- ------------------------------ -- Start the web server. -- ------------------------------ procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type) is begin Context.Console.Notice (N_INFO, "Starting..."); Command_Drivers.WS.Start; end Start_Server; -- ------------------------------ -- Wait for the server to shutdown. -- ------------------------------ procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type) is procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then AWA.Applications.Application'Class (Application.all).Close; end if; end Shutdown; Address : GNAT.Sockets.Sock_Addr_Type; Listen : GNAT.Sockets.Socket_Type; Socket : GNAT.Sockets.Socket_Type; begin GNAT.Sockets.Create_Socket (Listen); Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; if Command.Management_Port > 0 then Address.Port := Port_Type (Command.Management_Port); else Address.Port := 0; end if; GNAT.Sockets.Bind_Socket (Listen, Address); GNAT.Sockets.Listen_Socket (Listen); loop GNAT.Sockets.Accept_Socket (Listen, Socket, Address); exit; end loop; GNAT.Sockets.Close_Socket (Socket); GNAT.Sockets.Close_Socket (Listen); Command_Drivers.WS.Iterate (Shutdown'Access); end Wait_Server; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); GC.Define_Switch (Config => Config, Output => Command.Listening_Port'Access, Switch => "-p:", Long_Switch => "--port=", Initial => Command.Listening_Port, Argument => "NUMBER", Help => -("The server listening port")); GC.Define_Switch (Config => Config, Output => Command.Max_Connection'Access, Switch => "-C:", Long_Switch => "--connection=", Initial => Command.Max_Connection, Argument => "NUMBER", Help => -("The number of connections handled")); GC.Define_Switch (Config => Config, Output => Command.Upload'Access, Switch => "-u:", Long_Switch => "--upload=", Argument => "PATH", Help => -("The server upload directory")); GC.Define_Switch (Config => Config, Output => Command.TCP_No_Delay'Access, Switch => "-n", Long_Switch => "--tcp-no-delay", Help => -("Enable the TCP no delay option")); if Sys_Daemon'Address /= System.Null_Address then GC.Define_Switch (Config => Config, Output => Command.Daemon'Access, Switch => "-d", Long_Switch => "--daemon", Help => -("Run the server in the background")); end if; AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; begin Command_Drivers.Driver.Add_Command ("start", -("start the web server"), Command'Access); end AWA.Commands.Start;
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Servlet.Core; with Servlet.Server; with GNAT.Sockets; with AWA.Applications; package body AWA.Commands.Start is use Ada.Strings.Unbounded; use GNAT.Sockets; use type System.Address; -- ------------------------------ -- Start the server and all the application that have been registered. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Configure_Server (Context); Command.Configure_Applications (Context); Command.Start_Server (Context); Command.Wait_Server (Context); end Execute; -- ------------------------------ -- Configure the web server container before applications are registered. -- ------------------------------ procedure Configure_Server (Command : in out Command_Type; Context : in out Context_Type) is Config : Servlet.Server.Configuration; begin -- If daemon(3) is available and -d is defined, run it so that the parent -- process terminates and the child process continues. if Command.Daemon and Sys_Daemon'Address /= System.Null_Address then declare Result : constant Integer := Sys_Daemon (1, 0); begin if Result /= 0 then Context.Console.Error ("Cannot run in background"); end if; end; end if; Config.Listening_Port := Command.Listening_Port; Config.Max_Connection := Command.Max_Connection; Config.TCP_No_Delay := Command.TCP_No_Delay; if Command.Upload'Length > 0 then Config.Upload_Directory := To_Unbounded_String (Command.Upload.all); end if; Command_Drivers.WS.Configure (Config); end Configure_Server; -- ------------------------------ -- Configure all registered applications. -- ------------------------------ procedure Configure_Applications (Command : in out Command_Type; Context : in out Context_Type) is procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in ASF.Applications.Main.Application'Class then Configure (ASF.Applications.Main.Application'Class (Application.all), URI (URI'First + 1 .. URI'Last), Context); Count := Count + 1; end if; end Configure; Config : Servlet.Server.Configuration; begin Command_Drivers.WS.Iterate (Configure'Access); if Count = 0 then Context.Console.Error (-("There is no application")); return; end if; end Configure_Applications; -- ------------------------------ -- Start the web server. -- ------------------------------ procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type) is begin Context.Console.Notice (N_INFO, "Starting..."); Command_Drivers.WS.Start; end Start_Server; -- ------------------------------ -- Wait for the server to shutdown. -- ------------------------------ procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type) is procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then AWA.Applications.Application'Class (Application.all).Close; end if; end Shutdown; Address : GNAT.Sockets.Sock_Addr_Type; Listen : GNAT.Sockets.Socket_Type; Socket : GNAT.Sockets.Socket_Type; begin GNAT.Sockets.Create_Socket (Listen); Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; if Command.Management_Port > 0 then Address.Port := Port_Type (Command.Management_Port); else Address.Port := 0; end if; GNAT.Sockets.Bind_Socket (Listen, Address); GNAT.Sockets.Listen_Socket (Listen); loop GNAT.Sockets.Accept_Socket (Listen, Socket, Address); exit; end loop; GNAT.Sockets.Close_Socket (Socket); GNAT.Sockets.Close_Socket (Listen); Command_Drivers.WS.Iterate (Shutdown'Access); end Wait_Server; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); GC.Define_Switch (Config => Config, Output => Command.Listening_Port'Access, Switch => "-p:", Long_Switch => "--port=", Initial => Command.Listening_Port, Argument => "NUMBER", Help => -("The server listening port")); GC.Define_Switch (Config => Config, Output => Command.Max_Connection'Access, Switch => "-C:", Long_Switch => "--connection=", Initial => Command.Max_Connection, Argument => "NUMBER", Help => -("The number of connections handled")); GC.Define_Switch (Config => Config, Output => Command.Upload'Access, Switch => "-u:", Long_Switch => "--upload=", Argument => "PATH", Help => -("The server upload directory")); GC.Define_Switch (Config => Config, Output => Command.TCP_No_Delay'Access, Switch => "-n", Long_Switch => "--tcp-no-delay", Help => -("Enable the TCP no delay option")); if Sys_Daemon'Address /= System.Null_Address then GC.Define_Switch (Config => Config, Output => Command.Daemon'Access, Switch => "-d", Long_Switch => "--daemon", Help => -("Run the server in the background")); end if; AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; begin Command_Drivers.Driver.Add_Command ("start", -("start the web server"), Command'Access); end AWA.Commands.Start;
Update to configure the ASF application also (ie, not only AWA application)
Update to configure the ASF application also (ie, not only AWA application)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
789fdc7b66c500003163832e08c6133dbed0e3b3
src/gl/implementation/gl-objects.adb
src/gl/implementation/gl-objects.adb
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Deallocation; package body GL.Objects is overriding procedure Initialize (Object : in out GL_Object) is begin Object.Reference := new GL_Object_Reference'(GL_Id => 0, Reference_Count => 1, Initialized => False); GL_Object'Class (Object).Initialize_Id; end Initialize; overriding procedure Adjust (Object : in out GL_Object) is begin if Object.Reference /= null then Object.Reference.Reference_Count := Object.Reference.Reference_Count + 1; end if; end Adjust; overriding procedure Finalize (Object : in out GL_Object) is procedure Free is new Ada.Unchecked_Deallocation (Object => GL_Object_Reference, Name => GL_Object_Reference_Access); begin if Object.Reference /= null then Object.Reference.Reference_Count := Object.Reference.Reference_Count - 1; if Object.Reference.Reference_Count = 0 then if Object.Reference.Initialized then GL_Object'Class (Object).Delete_Id; end if; Free (Object.Reference); end if; end if; end Finalize; function Initialized (Object : GL_Object) return Boolean is begin return Object.Reference.Initialized; end Initialized; function Raw_Id (Object : GL_Object) return UInt is begin return Object.Reference.GL_Id; end Raw_Id; procedure Set_Raw_Id (Object : GL_Object; Id : UInt) is begin Object.Reference.GL_Id := Id; end Set_Raw_Id; overriding function "=" (Left, Right : GL_Object) return Boolean is begin return Left.Reference = Right.Reference; end "="; end GL.Objects;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Deallocation; package body GL.Objects is overriding procedure Initialize (Object : in out GL_Object) is begin Object.Reference := new GL_Object_Reference'(GL_Id => 0, Reference_Count => 1, Initialized => False); GL_Object'Class (Object).Initialize_Id; end Initialize; overriding procedure Adjust (Object : in out GL_Object) is begin if Object.Reference /= null then Object.Reference.Reference_Count := Object.Reference.Reference_Count + 1; end if; end Adjust; overriding procedure Finalize (Object : in out GL_Object) is procedure Free is new Ada.Unchecked_Deallocation (Object => GL_Object_Reference, Name => GL_Object_Reference_Access); begin if Object.Reference /= null then Object.Reference.Reference_Count := Object.Reference.Reference_Count - 1; if Object.Reference.Reference_Count = 0 then if Object.Reference.Initialized then GL_Object'Class (Object).Delete_Id; end if; Free (Object.Reference); end if; end if; -- Idempotence: next call to Finalize has no effect Object.Reference := null; end Finalize; function Initialized (Object : GL_Object) return Boolean is begin return Object.Reference.Initialized; end Initialized; function Raw_Id (Object : GL_Object) return UInt is begin return Object.Reference.GL_Id; end Raw_Id; procedure Set_Raw_Id (Object : GL_Object; Id : UInt) is begin Object.Reference.GL_Id := Id; end Set_Raw_Id; overriding function "=" (Left, Right : GL_Object) return Boolean is begin return Left.Reference = Right.Reference; end "="; end GL.Objects;
Make sure GL_Object.Finalize is idempotent
gl: Make sure GL_Object.Finalize is idempotent Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
5d17fa272104748302d2dc75f32112023ee7bd3c
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Make the Policy type abstract and the Get_Name function abstract
Make the Policy type abstract and the Get_Name function abstract
Ada
apache-2.0
stcarrez/ada-security
7dd291e90d6819c0ff2c5d5aa42a9f4dcff19028
src/asf-sessions-factory.ads
src/asf-sessions-factory.ads
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package ASF.Sessions.Factory is type Session_Factory is new Ada.Finalization.Limited_Controlled with private; -- Create a new session procedure Create_Session (Factory : in out Session_Factory; Result : out Session); -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access); -- Deletes the session. procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session); -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session); -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration; -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration); -- Release all the sessions. overriding procedure Finalize (Factory : in out Session_Factory); private use Util.Strings; package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Session, Hash => Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Session_Cache is -- Find the session in the session cache. function Find (Id : in String) return Session; -- Insert the session in the session cache. procedure Insert (Sess : in Session); -- Remove the session from the session cache. procedure Delete (Sess : in out Session); -- Generate a random bitstream. procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array); -- Initialize the random generator. procedure Initialize; private -- Id to session map. Sessions : Session_Maps.Map; -- Random number generator used for ID generation. Random : Id_Random.Generator; end Session_Cache; type Session_Factory is new Ada.Finalization.Limited_Controlled with record -- The session cache. Sessions : Session_Cache; -- Max inactive time in seconds. Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end record; -- Initialize the session factory. overriding procedure Initialize (Factory : in out Session_Factory); end ASF.Sessions.Factory;
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package ASF.Sessions.Factory is type Session_Factory is new Ada.Finalization.Limited_Controlled with private; -- Create a new session procedure Create_Session (Factory : in out Session_Factory; Result : out Session); -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access); -- Deletes the session. procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session); -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session); -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration; -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration); -- Release all the sessions. overriding procedure Finalize (Factory : in out Session_Factory); private use Util.Strings; package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Session, Hash => Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Session_Cache is -- Find the session in the session cache. function Find (Id : in String) return Session; -- Insert the session in the session cache. procedure Insert (Sess : in Session); -- Remove the session from the session cache. procedure Delete (Sess : in out Session); -- Generate a random bitstream. procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array); -- Initialize the random generator. procedure Initialize; -- Clear the session cache. procedure Clear; private -- Id to session map. Sessions : Session_Maps.Map; -- Random number generator used for ID generation. Random : Id_Random.Generator; end Session_Cache; type Session_Factory is new Ada.Finalization.Limited_Controlled with record -- The session cache. Sessions : Session_Cache; -- Max inactive time in seconds. Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end record; -- Initialize the session factory. overriding procedure Initialize (Factory : in out Session_Factory); end ASF.Sessions.Factory;
Declare the Clear protected procedure
Declare the Clear protected procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f00af7f7e233104aef5a5a0646c29aa1a02fb0b4
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is -- Minimum length for the server private key (160 bits min length). -- (See NIST Special Publication 800-107) MIN_KEY_LENGTH : constant Positive := 20; Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Declare the MIN_KEY_LENGTH constant for the private key constraint
Declare the MIN_KEY_LENGTH constant for the private key constraint
Ada
apache-2.0
stcarrez/ada-security
5525a294f4623acd33840e3efd98f84c3e689843
src/gen-commands-propset.adb
src/gen-commands-propset.adb
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with GNAT.Command_Line; package body Gen.Commands.Propset is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; Name : constant String := Get_Argument; Value : constant String := Get_Argument; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Name, Value); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUEE"); New_Line; end Help; end Gen.Commands.Propset;
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Gen.Commands.Propset is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; begin if Args.Get_Count /= 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2)); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUEE"); New_Line; end Help; end Gen.Commands.Propset;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo