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
|
---|---|---|---|---|---|---|---|---|---|
05e64857dd5931f634ecdeab8107c0dc40cdc3f6
|
src/wiki-buffers.adb
|
src/wiki-buffers.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Wiki.Helpers;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
exit when Content = null;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WChar) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- Append in `Into` builder the `Content` builder starting at `From` position
-- and the up to and including the `To` position.
-- ------------------------------
procedure Append (Into : in out Builder;
Content : in Builder;
From : in Positive;
To : in Positive) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : constant Positive := Pos;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : constant Positive := From;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
-- ------------------------------
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
-- ------------------------------
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural) is
Block : Wiki.Buffers.Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
Main_Loop :
while Block /= null loop
declare
Last : constant Natural := Block.Last;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Block.Content (Pos)) loop
Pos := Pos + 1;
Count := Count + 1;
end loop;
exit Main_Loop when Pos <= Last;
end;
Block := Block.Next_Block;
Pos := 1;
end loop Main_Loop;
Buffer := Block;
From := Pos;
end Skip_Spaces;
-- ------------------------------
-- Skip one optional space or tab.
-- ------------------------------
procedure Skip_Optional_Space (Buffer : in out Buffer_Access;
From : in out Positive) is
begin
if From <= Buffer.Last
and then Wiki.Helpers.Is_Space (Buffer.Content (From))
then
Next (Buffer, From);
end if;
end Skip_Optional_Space;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Wiki.Helpers;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
exit when Content = null;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WChar) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- Append in `Into` builder the `Content` builder starting at `From` position
-- and the up to and including the `To` position.
-- ------------------------------
procedure Append (Into : in out Builder;
Content : in Builder;
From : in Positive;
To : in Positive) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : constant Positive := Pos;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : constant Positive := From;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
-- ------------------------------
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
-- ------------------------------
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural) is
Block : Wiki.Buffers.Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
Main_Loop :
while Block /= null loop
declare
Last : constant Natural := Block.Last;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Block.Content (Pos)) loop
Pos := Pos + 1;
Count := Count + 1;
end loop;
exit Main_Loop when Pos <= Last;
end;
Block := Block.Next_Block;
Pos := 1;
end loop Main_Loop;
Buffer := Block;
From := Pos;
end Skip_Spaces;
-- ------------------------------
-- Skip one optional space or tab.
-- ------------------------------
procedure Skip_Optional_Space (Buffer : in out Buffer_Access;
From : in out Positive) is
begin
if Buffer /= null and then From <= Buffer.Last
and then Wiki.Helpers.Is_Space (Buffer.Content (From))
then
Next (Buffer, From);
end if;
end Skip_Optional_Space;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
Fix Skip_Optional_Space in case it is called with a null buffer
|
Fix Skip_Optional_Space in case it is called with a null buffer
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c666b550fc12c0d046eab753a6f9233b24cbd826
|
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.Serialize.Contexts;
-- with Util.Serialize.Mappers;
with Util.Log.Loggers;
-- with Util.Stacks;
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;
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 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) 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) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural) 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;
Attribute : in Boolean := False) is abstract;
-- 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 Reader;
Message : in String) is abstract;
type Parser is abstract new Util.Serialize.Contexts.Context 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.Serialize.Contexts.Context 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;
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;
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 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;
|
Add a Logging class parameter to several operations of Reader interface Update Parser type to implement the Logging interface and avoid depending on the mapper context
|
Add a Logging class parameter to several operations of Reader interface
Update Parser type to implement the Logging interface and avoid depending
on the mapper context
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5f1f3cb173efb5793271edd76687f77e86d9b64e
|
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
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);
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;
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;
|
Declare the Initialize procedure
|
Declare the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a0139226b4ebdfe07d78b8a9e2ba4d564c39de56
|
src/sys/streams/util-streams-buffered-encoders.ads
|
src/sys/streams/util-streams-buffered-encoders.ads
|
-----------------------------------------------------------------------
-- util-streams-encoders -- Streams with encoding and decoding capabilities
-- 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.Encoders;
-- == Encoding Streams ==
-- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities.
-- The stream passes the data to be written to the <tt>Transformer</tt> interface that
-- allows to make transformations on the data before being written.
--
-- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream;
--
-- The encoding stream manages a buffer that is used to hold the encoded data before it is
-- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate
-- the target stream, the size of the buffer and the encoding format to be used.
--
-- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64");
--
package Util.Streams.Buffered.Encoders is
pragma Preelaborate;
-- -----------------------
-- Encoding stream
-- -----------------------
-- The <b>Encoding_Stream</b> is an output stream which uses an encoder to
-- transform the data before writing it to the output. The transformer can
-- change the data by encoding it in Base64, Base16 or encrypting it.
type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Encoding_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Encoding_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Encoding_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Encoding_Stream);
private
type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Transform : Util.Encoders.Transformer_Access;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Encoding_Stream);
end Util.Streams.Buffered.Encoders;
|
-----------------------------------------------------------------------
-- util-streams-encoders -- Streams with encoding and decoding capabilities
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders;
-- == Encoding Streams ==
-- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities.
-- The stream passes the data to be written to the <tt>Transformer</tt> interface that
-- allows to make transformations on the data before being written.
--
-- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream;
--
-- The encoding stream manages a buffer that is used to hold the encoded data before it is
-- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate
-- the target stream, the size of the buffer and the encoding format to be used.
--
-- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64");
--
package Util.Streams.Buffered.Encoders is
pragma Preelaborate;
-- -----------------------
-- Encoding stream
-- -----------------------
-- The <b>Encoding_Stream</b> is an output stream which uses an encoder to
-- transform the data before writing it to the output. The transformer can
-- change the data by encoding it in Base64, Base16 or encrypting it.
type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Encoding_Stream;
Output : access Output_Stream'Class;
Size : in Natural;
Format : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Encoding_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Encoding_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Encoding_Stream);
private
type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Transform : Util.Encoders.Transformer_Access;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Encoding_Stream);
end Util.Streams.Buffered.Encoders;
|
Use anonymous access type for the input and output streams
|
Use anonymous access type for the input and output streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
fe4d9abcacc551137e595ccc163a8a29ce05b798
|
mat/src/mat-consoles.ads
|
mat/src/mat-consoles.ads
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_THREAD,
F_COUNT);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
private
type Field_Size_Array is array (Field_Type) of Positive;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_THREAD,
F_COUNT);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
private
type Field_Size_Array is array (Field_Type) of Positive;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Define the End_Title procedure
|
Define the End_Title procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7d4691f499c4f1fd414ba658aba71cc7c40f68b3
|
matp/src/mat-formats.adb
|
matp/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- 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 Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Hex_Length : Positive := 16;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
function Event_Malloc (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;
function Event_Free (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;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- 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 is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- 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 is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
function Event_Malloc (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 is
Free_Event : MAT.Events.Target_Event_Type;
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated (never freed)";
end Event_Malloc;
function Event_Free (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 is
Alloc_Event : MAT.Events.Target_Event_Type;
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- ------------------------------
-- 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 is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format the difference between two event IDs (offset).
-- ------------------------------
function Offset (First : in MAT.Events.Event_Id_Type;
Second : in MAT.Events.Event_Id_Type) return String is
use type MAT.Events.Event_Id_Type;
begin
if First = Second or First = 0 or Second = 0 then
return "";
elsif First > Second then
return "+" & Util.Strings.Image (Natural (First - Second));
else
return "-" & Util.Strings.Image (Natural (Second - First));
end if;
end Offset;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
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 Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Hex_Length : Positive := 16;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
function Event_Malloc (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;
function Event_Free (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;
-- ------------------------------
-- Set the size of a target address to format them.
-- ------------------------------
procedure Set_Address_Size (Size : in Positive) is
begin
Hex_Length := Size;
end Set_Address_Size;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- 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 is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- 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 is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
function Event_Malloc (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 is
Free_Event : MAT.Events.Target_Event_Type;
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated (never freed)";
end Event_Malloc;
function Event_Free (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 is
Alloc_Event : MAT.Events.Target_Event_Type;
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- ------------------------------
-- 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 is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format the difference between two event IDs (offset).
-- ------------------------------
function Offset (First : in MAT.Events.Event_Id_Type;
Second : in MAT.Events.Event_Id_Type) return String is
use type MAT.Events.Event_Id_Type;
begin
if First = Second or First = 0 or Second = 0 then
return "";
elsif First > Second then
return "+" & Util.Strings.Image (Natural (First - Second));
else
return "-" & Util.Strings.Image (Natural (Second - First));
end if;
end Offset;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
end MAT.Formats;
|
Implement the Set_Address_Size procedure
|
Implement the Set_Address_Size procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
fbbb7014c39573c2650750aa8ba46830f3f8b9f3
|
src/base/commands/util-commands-drivers.adb
|
src/base/commands/util-commands-drivers.adb
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Strings.Formats;
with Ada.Text_IO; use Ada.Text_IO;
package body Util.Commands.Drivers is
use Ada.Strings.Unbounded;
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
function "-" (Message : in String) return String is (Translate (Message)) with Inline;
-- ------------------------------
-- Get the description associated with the command.
-- ------------------------------
function Get_Description (Command : in Command_Type) return String is
begin
return To_String (Command.Description);
end Get_Description;
-- ------------------------------
-- Get the name used to register the command.
-- ------------------------------
function Get_Name (Command : in Command_Type) return String is
begin
return To_String (Command.Name);
end Get_Name;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
Config : Config_Type;
begin
Command_Type'Class (Command).Setup (Config, Context);
Config_Parser.Usage (Name, Config);
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 out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Compute_Size (Position : in Command_Sets.Cursor);
procedure Print (Position : in Command_Sets.Cursor);
Column : Ada.Text_IO.Positive_Count := 1;
procedure Compute_Size (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
Len : constant Natural := Length (Cmd.Name);
begin
if Natural (Column) < Len then
Column := Ada.Text_IO.Positive_Count (Len);
end if;
end Compute_Size;
procedure Print (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
begin
Put (" ");
Put (To_String (Cmd.Name));
if Length (Cmd.Description) > 0 then
Set_Col (Column + 7);
Put (To_String (Cmd.Description));
end if;
New_Line;
end Print;
begin
Logs.Debug ("Execute command {0}", Name);
if Args.Get_Count = 0 then
Usage (Command.Driver.all, Args, Context);
New_Line;
Put_Line (Strings.Formats.Format (-("Type '{0} help {command}' for help "
& "on a specific command."), Driver_Name));
Put_Line (-("Available subcommands:"));
Put (Driver_Name);
Command.Driver.List.Iterate (Process => Compute_Size'Access);
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);
raise Not_Found;
else
Target_Cmd.Help (Cmd_Name, Context);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
-- ------------------------------
-- Report the command usage.
-- ------------------------------
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
Put_Line (To_String (Driver.Desc));
New_Line;
if Name'Length > 0 then
declare
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Usage (Name, Context);
else
Put (-("Invalid command"));
end if;
end;
else
Put (-("Usage: "));
Put (Args.Get_Command_Name);
Put (" ");
Put_Line (To_String (Driver.Usage));
end if;
end Usage;
-- ------------------------------
-- 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;
-- ------------------------------
-- Set the driver usage printed in the usage.
-- ------------------------------
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String) is
begin
Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage);
end Set_Usage;
-- ------------------------------
-- 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.Name := To_Unbounded_String (Name);
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Command);
end Add_Command;
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Description := To_Unbounded_String (Description);
Add_Command (Driver, Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler) is
Command : constant Command_Access
:= new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Description => To_Unbounded_String (Description),
Name => To_Unbounded_String (Name),
Handler => Handler);
begin
Driver.List.Include (Command);
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
Cmd : aliased Help_Command_Type;
Pos : Command_Sets.Cursor;
begin
Cmd.Name := To_Unbounded_String (Name);
Pos := Driver.List.Find (Cmd'Unchecked_Access);
if Command_Sets.Has_Element (Pos) then
return Command_Sets.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
procedure Execute (Cmd_Args : in Argument_List'Class);
Command : constant Command_Access := Driver.Find_Command (Name);
procedure Execute (Cmd_Args : in Argument_List'Class) is
begin
Command.Execute (Name, Cmd_Args, Context);
end Execute;
begin
if Command /= null then
declare
Config : Config_Type;
begin
Command.Setup (Config, Context);
Config_Parser.Execute (Config, Args, Execute'Access);
end;
else
Logs.Error (-("Unknown command '{0}'"), Name);
raise Not_Found;
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
pragma Unreferenced (Driver);
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out 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 out Handler_Command_Type;
Name : in String;
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, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Strings.Formats;
with Ada.Text_IO; use Ada.Text_IO;
package body Util.Commands.Drivers is
use Ada.Strings.Unbounded;
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
function "-" (Message : in String) return String is (Translate (Message)) with Inline;
-- ------------------------------
-- Get the description associated with the command.
-- ------------------------------
function Get_Description (Command : in Command_Type) return String is
begin
return To_String (Command.Description);
end Get_Description;
-- ------------------------------
-- Get the name used to register the command.
-- ------------------------------
function Get_Name (Command : in Command_Type) return String is
begin
return To_String (Command.Name);
end Get_Name;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
Config : Config_Type;
begin
Command_Type'Class (Command).Setup (Config, Context);
Config_Parser.Usage (Name, Config);
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 out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Compute_Size (Position : in Command_Sets.Cursor);
procedure Print (Position : in Command_Sets.Cursor);
Column : Ada.Text_IO.Positive_Count := 1;
procedure Compute_Size (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
Len : constant Natural := Length (Cmd.Name);
begin
if Natural (Column) < Len then
Column := Ada.Text_IO.Positive_Count (Len);
end if;
end Compute_Size;
procedure Print (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
begin
Put (" ");
Put (To_String (Cmd.Name));
if Length (Cmd.Description) > 0 then
Set_Col (Column + 7);
Put (To_String (Cmd.Description));
end if;
New_Line;
end Print;
begin
Logs.Debug ("Execute command {0}", Name);
if Args.Get_Count = 0 then
Usage (Command.Driver.all, Args, Context);
New_Line;
Put_Line (Strings.Formats.Format (-("Type '{0} help {command}' for help "
& "on a specific command."), Driver_Name));
Put_Line (-("Available subcommands:"));
Command.Driver.List.Iterate (Process => Compute_Size'Access);
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);
raise Not_Found;
else
Target_Cmd.Help (Cmd_Name, Context);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
-- ------------------------------
-- Report the command usage.
-- ------------------------------
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
Put_Line (To_String (Driver.Desc));
New_Line;
if Name'Length > 0 then
declare
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Usage (Name, Context);
else
Put (-("Invalid command"));
end if;
end;
else
Put (-("Usage: "));
Put (Args.Get_Command_Name);
Put (" ");
Put_Line (To_String (Driver.Usage));
end if;
end Usage;
-- ------------------------------
-- 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;
-- ------------------------------
-- Set the driver usage printed in the usage.
-- ------------------------------
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String) is
begin
Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage);
end Set_Usage;
-- ------------------------------
-- 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.Name := To_Unbounded_String (Name);
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Command);
end Add_Command;
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Description := To_Unbounded_String (Description);
Add_Command (Driver, Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler) is
Command : constant Command_Access
:= new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Description => To_Unbounded_String (Description),
Name => To_Unbounded_String (Name),
Handler => Handler);
begin
Driver.List.Include (Command);
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
Cmd : aliased Help_Command_Type;
Pos : Command_Sets.Cursor;
begin
Cmd.Name := To_Unbounded_String (Name);
Pos := Driver.List.Find (Cmd'Unchecked_Access);
if Command_Sets.Has_Element (Pos) then
return Command_Sets.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
procedure Execute (Cmd_Args : in Argument_List'Class);
Command : constant Command_Access := Driver.Find_Command (Name);
procedure Execute (Cmd_Args : in Argument_List'Class) is
begin
Command.Execute (Name, Cmd_Args, Context);
end Execute;
begin
if Command /= null then
declare
Config : Config_Type;
begin
Command.Setup (Config, Context);
Config_Parser.Execute (Config, Args, Execute'Access);
end;
else
Logs.Error (-("Unknown command '{0}'"), Name);
raise Not_Found;
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
pragma Unreferenced (Driver);
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out 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 out Handler_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
Remove spurious Put (Driver_Name) in the output
|
Remove spurious Put (Driver_Name) in the output
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c8178e997ce58f1f5b6a24ec4333bd0d9c8ec505
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- 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 ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Statements;
with ADO.Utils;
with AWA.Services.Contexts;
package body AWA.Comments.Beans is
package ASC renames AWA.Services.Contexts;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "comment" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Create_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- 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 ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with AWA.Services.Contexts;
package body AWA.Comments.Beans is
package ASC renames AWA.Services.Contexts;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "comment" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Create_Comment (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
Fix the implementation of Load_Comments Implement the new form of Load_Comments procedure
|
Fix the implementation of Load_Comments
Implement the new form of Load_Comments procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6533911296b7962037ccbbd45fbf5210c58ef9a4
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- 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 ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with ADO.Parameters;
with AWA.Helpers.Requests;
package body AWA.Comments.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "message" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
if Id /= ADO.NO_IDENTIFIER then
From.Set_Entity_Id (ADO.Utils.To_Identifier (Value));
end if;
end;
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "format" then
From.Set_Format (AWA.Comments.Models.Format_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the comment.
-- ------------------------------
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Create_Comment (Permission => To_String (Bean.Permission),
Entity_Type => To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- ------------------------------
-- Save the comment.
-- ------------------------------
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Update_Comment (Permission => To_String (Bean.Permission),
Comment => Bean);
end Save;
-- ------------------------------
-- Publish or not the comment.
-- ------------------------------
overriding
procedure Publish (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission),
Id => Id,
Status => Models.Status_Type_Objects.To_Value (Value),
Comment => Bean);
end Publish;
-- ------------------------------
-- Delete the comment.
-- ------------------------------
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
elsif Name = "sort" then
if Util.Beans.Objects.To_String (Value) = "oldest" then
From.Oldest_First := True;
else
From.Oldest_First := False;
end if;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
if Into.Oldest_First then
Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC"));
else
Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC"));
end if;
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with ADO.Parameters;
with AWA.Helpers.Requests;
package body AWA.Comments.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
if Id /= ADO.NO_IDENTIFIER then
From.Set_Entity_Id (ADO.Utils.To_Identifier (Value));
end if;
end;
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
else
AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value);
end if;
end Set_Value;
-- ------------------------------
-- Create the comment.
-- ------------------------------
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Create_Comment (Permission => To_String (Bean.Permission),
Entity_Type => To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- ------------------------------
-- Save the comment.
-- ------------------------------
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Update_Comment (Permission => To_String (Bean.Permission),
Comment => Bean);
end Save;
-- ------------------------------
-- Publish or not the comment.
-- ------------------------------
overriding
procedure Publish (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission),
Id => Id,
Status => Models.Status_Type_Objects.To_Value (Value),
Comment => Bean);
end Publish;
-- ------------------------------
-- Delete the comment.
-- ------------------------------
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
elsif Name = "sort" then
if Util.Beans.Objects.To_String (Value) = "oldest" then
From.Oldest_First := True;
else
From.Oldest_First := False;
end if;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
if Into.Oldest_First then
Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC"));
else
Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC"));
end if;
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
Use the generated Set_Value procedure for the Comment_Bean Set_Value implementation
|
Use the generated Set_Value procedure for the Comment_Bean Set_Value implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4fc702d00f503a9386bd2e0d2a3443ef8e2fa5cd
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 2013, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type ADO.Identifier;
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
Id : ADO.Identifier;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then
Id := ADO.Utils.To_Identifier (Value);
if Id /= ADO.NO_IDENTIFIER then
Manager.Load_Storage (From, Id);
end if;
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
if Part.Get_Size > 100_000 then
Manager.Save (Bean, Part, AWA.Storages.Models.FILE);
else
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end if;
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (1).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
if not List.Init_Flags (INIT_FOLDER) then
Load_Folder (List);
end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 2013, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type ADO.Identifier;
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
Id : ADO.Identifier;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then
Id := ADO.Utils.To_Identifier (Value);
if Id /= ADO.NO_IDENTIFIER then
Manager.Load_Storage (From, Id);
end if;
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
if Part.Get_Size > 100_000 then
Manager.Save (Bean, Part, AWA.Storages.Models.FILE);
else
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end if;
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (1).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
if not List.Init_Flags (INIT_FOLDER) then
Load_Folder (List);
end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
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
|
c9f56f3397587faf232a024cf1bf9a903b7425f5
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_NONE,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_TOC_DISPLAY,
N_PARAGRAPH,
N_LIST_ITEM_END,
N_LIST_END,
N_NUM_LIST_END,
N_LIST_ITEM,
N_END_DEFINITION,
N_NEWLINE,
N_HEADER,
N_DEFINITION,
N_TOC,
N_TOC_ENTRY,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_PREFORMAT,
N_TABLE,
N_ROW,
N_COLUMN,
N_LIST_START,
N_NUM_LIST_START,
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_NONE .. N_NEWLINE;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
Parent : Node_Type_Access;
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY
| N_NUM_LIST_START | N_LIST_START | N_DEFINITION =>
Level : Natural := 0;
Header : Wiki.Strings.WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START | N_TABLE | N_ROW | N_COLUMN =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
when N_PREFORMAT =>
Language : Wiki.Strings.UString;
Preformatted : Wiki.Strings.WString (1 .. Len);
when N_TOC =>
Entries : Node_List_Access;
when others =>
null;
end case;
end record;
-- Append a node to the tag node.
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access);
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Finalize the node list to release the allocated memory.
procedure Finalize (List : in out Node_List);
private
NODE_LIST_BLOCK_SIZE : constant Positive := 16;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_NONE,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_TOC_DISPLAY,
N_PARAGRAPH,
N_LIST_ITEM_END,
N_LIST_END,
N_NUM_LIST_END,
N_LIST_ITEM,
N_END_DEFINITION,
N_NEWLINE,
N_TOC_ENTRY,
-- Nodes with level and content.
N_HEADER,
N_BLOCKQUOTE,
N_INDENT,
N_NUM_LIST_START,
N_LIST_START,
N_DEFINITION,
-- Nodes with children and attributes.
N_TAG_START,
N_TABLE,
N_ROW,
N_COLUMN,
N_TOC,
N_QUOTE,
N_PREFORMAT,
N_TEXT,
N_LINK,
N_LINK_REF,
N_LINK_REF_END,
N_IMAGE);
-- Node kinds which are simple markers in the document.
subtype Simple_Node_Kind is Node_Kind range N_NONE .. N_NEWLINE;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
Parent : Node_Type_Access;
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT
| N_NUM_LIST_START | N_LIST_START | N_DEFINITION =>
Level : Natural := 0;
Content : Node_List_Access;
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE | N_LINK_REF =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START | N_TABLE | N_ROW | N_COLUMN =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
when N_PREFORMAT =>
Language : Wiki.Strings.UString;
Preformatted : Wiki.Strings.WString (1 .. Len);
when N_TOC_ENTRY =>
Header : Wiki.Strings.WString (1 .. Len);
Toc_Level : Natural := 0;
when N_TOC =>
Entries : Node_List_Access;
when others =>
null;
end case;
end record;
-- Append a node to the tag node.
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access);
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Finalize the node list to release the allocated memory.
procedure Finalize (List : in out Node_List);
private
NODE_LIST_BLOCK_SIZE : constant Positive := 16;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
end Wiki.Nodes;
|
Update the node types to allow representing link references and headers with specific formatting contents
|
Update the node types to allow representing link references and headers with specific formatting contents
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8847b52e54a1c868853e48917345a7f15503bf16
|
awa/src/awa-events-dispatchers-tasks.adb
|
awa/src/awa-events-dispatchers-tasks.adb
|
-----------------------------------------------------------------------
-- awa-events-dispatchers-tasks -- AWA Event Dispatchers
-- Copyright (C) 2012, 2015, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with AWA.Services.Contexts;
package body AWA.Events.Dispatchers.Tasks is
use Util.Log;
use Ada.Strings.Unbounded;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Tasks");
-- ------------------------------
-- Start the dispatcher.
-- ------------------------------
overriding
procedure Start (Manager : in out Task_Dispatcher) is
begin
if Manager.Queues.Get_Count > 0 then
Log.Info ("Starting the tasks");
if Manager.Workers = null then
Manager.Workers := new Consumer_Array (1 .. Manager.Task_Count);
end if;
for I in Manager.Workers'Range loop
Manager.Workers (I).Start (Manager'Unchecked_Access);
end loop;
else
Log.Info ("No event dispatcher task started (no event queue to poll)");
end if;
end Start;
-- ------------------------------
-- Stop the dispatcher.
-- ------------------------------
overriding
procedure Stop (Manager : in out Task_Dispatcher) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Consumer_Array,
Name => Consumer_Array_Access);
begin
if Manager.Workers /= null then
Log.Info ("Stopping the event dispatcher tasks");
for I in Manager.Workers'Range loop
if Manager.Workers (I)'Callable then
Manager.Workers (I).Stop;
else
Log.Error ("Event consumer task terminated abnormally");
end if;
end loop;
Free (Manager.Workers);
end if;
end Stop;
procedure Add_Queue (Manager : in out Task_Dispatcher;
Queue : in AWA.Events.Queues.Queue_Ref;
Added : out Boolean) is
begin
Log.Info ("Adding queue {0} to the task dispatcher", Queue.Get_Name);
Manager.Queues.Enqueue (Queue);
Added := True;
end Add_Queue;
function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access;
Match : in String;
Count : in Positive;
Priority : in Positive) return Dispatcher_Access is
Result : constant Task_Dispatcher_Access := new Task_Dispatcher;
begin
Result.Task_Count := Count;
Result.Priority := Priority;
Result.Match := To_Unbounded_String (Match);
Result.Manager := Service.all'Access;
return Result.all'Access;
end Create_Dispatcher;
task body Consumer is
Dispatcher : Task_Dispatcher_Access;
Time : Duration := 0.01;
Do_Work : Boolean := True;
begin
Log.Info ("Event consumer is ready");
select
accept Start (D : in Task_Dispatcher_Access) do
Dispatcher := D;
end Start;
Log.Info ("Event consumer is started");
while Do_Work loop
declare
Nb_Queues : constant Natural := Dispatcher.Queues.Get_Count;
Queue : AWA.Events.Queues.Queue_Ref;
Nb_Events : Natural := 0;
Context : AWA.Services.Contexts.Service_Context;
begin
-- Set the service context.
Context.Set_Context (Application => Dispatcher.Manager.Get_Application.all'Access,
Principal => null);
-- We can have several tasks that dispatch events from several queues.
-- Each queue in the list must be given the same polling quota.
-- Pick a queue and dispatch some pending events.
-- Put back the queue in the fifo.
for I in 1 .. Nb_Queues loop
Dispatcher.Queues.Dequeue (Queue);
begin
Dispatcher.Dispatch (Queue, Nb_Events);
exception
when E : others =>
Log.Error ("Exception when dispatching events", E, True);
end;
Dispatcher.Queues.Enqueue (Queue);
end loop;
-- If we processed something, reset the timeout delay and continue polling.
-- Otherwise, double the sleep time.
if Nb_Events /= 0 then
Time := 0.01;
else
Log.Debug ("Sleeping {0} seconds", Duration'Image (Time));
select
accept Stop do
Do_Work := False;
end Stop;
or
accept Start (D : in Task_Dispatcher_Access) do
Dispatcher := D;
end Start;
or
delay Time;
end select;
if Time < 60.0 then
Time := Time * 2.0;
end if;
end if;
end;
end loop;
or
terminate;
end select;
end Consumer;
end AWA.Events.Dispatchers.Tasks;
|
-----------------------------------------------------------------------
-- awa-events-dispatchers-tasks -- AWA Event Dispatchers
-- Copyright (C) 2012, 2015, 2017, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with AWA.Services.Contexts;
package body AWA.Events.Dispatchers.Tasks is
use Util.Log;
use Ada.Strings.Unbounded;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Tasks");
-- ------------------------------
-- Start the dispatcher.
-- ------------------------------
overriding
procedure Start (Manager : in out Task_Dispatcher) is
begin
if Manager.Queues.Get_Count > 0 then
Log.Info ("Starting the tasks");
if Manager.Workers = null then
Manager.Workers := new Consumer_Array (1 .. Manager.Task_Count);
end if;
for I in Manager.Workers'Range loop
Manager.Workers (I).Start (Manager'Unchecked_Access);
end loop;
else
Log.Info ("No event dispatcher task started (no event queue to poll)");
end if;
end Start;
-- ------------------------------
-- Stop the dispatcher.
-- ------------------------------
overriding
procedure Stop (Manager : in out Task_Dispatcher) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Consumer_Array,
Name => Consumer_Array_Access);
begin
if Manager.Workers /= null then
Log.Info ("Stopping the event dispatcher tasks");
for I in Manager.Workers'Range loop
if Manager.Workers (I)'Callable then
Manager.Workers (I).Stop;
else
Log.Error ("Event consumer task terminated abnormally");
end if;
end loop;
Free (Manager.Workers);
end if;
end Stop;
-- ------------------------------
-- Inform the dispatch that some events may have been queued.
-- ------------------------------
overriding
procedure Update (Manager : in Task_Dispatcher;
Queue : in Queues.Queue_Ref) is
pragma Unreferenced (Queue);
begin
if Manager.Workers /= null then
Log.Debug ("Wakeup dispatcher tasks");
for I in Manager.Workers'Range loop
if Manager.Workers (I)'Callable then
Manager.Workers (I).Wakeup;
else
Log.Error ("Event consumer task terminated abnormally");
end if;
end loop;
end if;
end Update;
procedure Add_Queue (Manager : in out Task_Dispatcher;
Queue : in AWA.Events.Queues.Queue_Ref;
Added : out Boolean) is
begin
Log.Info ("Adding queue {0} to the task dispatcher", Queue.Get_Name);
Manager.Queues.Enqueue (Queue);
Queue.Add_Listener (Manager'Unchecked_Access);
Added := True;
end Add_Queue;
function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access;
Match : in String;
Count : in Positive;
Priority : in Positive) return Dispatcher_Access is
Result : constant Task_Dispatcher_Access := new Task_Dispatcher;
begin
Result.Task_Count := Count;
Result.Priority := Priority;
Result.Match := To_Unbounded_String (Match);
Result.Manager := Service.all'Access;
return Result.all'Access;
end Create_Dispatcher;
task body Consumer is
Dispatcher : Task_Dispatcher_Access;
Time : Duration := 0.01;
Do_Work : Boolean := True;
begin
Log.Info ("Event consumer is ready");
select
accept Start (D : in Task_Dispatcher_Access) do
Dispatcher := D;
end Start;
Log.Info ("Event consumer is started");
while Do_Work loop
declare
Nb_Queues : constant Natural := Dispatcher.Queues.Get_Count;
Queue : AWA.Events.Queues.Queue_Ref;
Nb_Events : Natural := 0;
Context : AWA.Services.Contexts.Service_Context;
begin
-- Set the service context.
Context.Set_Context (Application => Dispatcher.Manager.Get_Application.all'Access,
Principal => null);
-- We can have several tasks that dispatch events from several queues.
-- Each queue in the list must be given the same polling quota.
-- Pick a queue and dispatch some pending events.
-- Put back the queue in the fifo.
for I in 1 .. Nb_Queues loop
Dispatcher.Queues.Dequeue (Queue);
begin
Dispatcher.Dispatch (Queue, Nb_Events);
exception
when E : others =>
Log.Error ("Exception when dispatching events", E, True);
end;
Dispatcher.Queues.Enqueue (Queue);
end loop;
-- If we processed something, reset the timeout delay and continue polling.
-- Otherwise, double the sleep time.
if Nb_Events /= 0 then
Time := 0.01;
else
Log.Debug ("Sleeping {0} seconds", Duration'Image (Time));
select
accept Stop do
Do_Work := False;
end Stop;
or
accept Wakeup do
Do_Work := True;
end Wakeup;
or
accept Start (D : in Task_Dispatcher_Access) do
Dispatcher := D;
end Start;
or
delay Time;
end select;
if Time < 60.0 then
Time := Time * 2.0;
end if;
end if;
end;
end loop;
or
terminate;
end select;
end Consumer;
end AWA.Events.Dispatchers.Tasks;
|
Implement the Update procedure and wakeup the tasks if necessary
|
Implement the Update procedure and wakeup the tasks if necessary
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2d217932f804871551897d6f19fe71b81d41e296
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
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 Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (File : in Query_File_Info) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", File.Path.all);
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
use ADO.Drivers;
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).Set (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;
begin
Log.Info ("Reading XML query {0}", File.Path.all);
-- Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
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 (File.Path.all, 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", File.Path.all);
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).Get.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.Drivers.Connections.Configuration'Class) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
Pos : Query_Index_Table := 1;
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);
Query : Query_Definition_Access := File.Queries;
begin
Manager.Files (File.File).File := File;
Manager.Files (File.File).Path := new 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.Query := 0;
Query.File := File;
Query.Next := null;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
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 Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (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
use ADO.Drivers;
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).Set (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", 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).Get.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.Drivers.Connections.Configuration'Class) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
Pos : Query_Index_Table := 1;
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);
Query : Query_Definition_Access := File.Queries;
begin
Manager.Files (File.File).File := File;
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.Query := 0;
Query.File := File;
Query.Next := null;
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Use a Unbounded_String to hold the file's path
|
Use a Unbounded_String to hold the file's path
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
52142b0cbeeb99e389cf18f14f1ee3c73dbb42f2
|
t0047.adb
|
t0047.adb
|
-- t0047.adb - Sat Feb 1 16:15:50 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- $Id$
--
-- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991
with Ada.Text_IO, System;
with Posix;
use Posix;
procedure T0047 is
use Ada.Text_IO;
I, J, L : int_t;
K : ushort_t;
Ctl_Buf : uchar_array(1..128);
Ctl_Len : uint64_t;
Len : Natural;
Ctl_Level : int_t;
Ctl_Type : int_t;
Offset : uint64_t;
Data_Len : uint64_t;
Accepted : Boolean;
Received : Boolean;
Fd1, Fd2 : fd_t := -1;
Fd3 : fd_t := -1;
Child : pid_t := -1;
Error : errno_t;
begin
Put_Line("Test 0047 - Put/Get_Cmsg");
I := 98;
J := 95;
K := 23;
L := 29;
-- Put control messages into Ctl_Buf
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf,Ctl_Len,1,11,I'Address,I'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,2,12,J'Address,J'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,3,13,K'Address,K'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,4,14,L'Address,L'Size/8,Accepted);
pragma Assert(Accepted);
pragma Assert(Ctl_Len > 8);
Put_Line("Ctl_Len =" & uint64_t'Image(Ctl_Len));
I := 0;
J := 0;
K := 0;
L := 0;
-- Get control messages back from Ctl_Buf
Offset := 0;
Len := Natural(Ctl_Len);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 1);
pragma Assert(Ctl_Type = 11);
Data_Len := I'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,I'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= I'Size/8);
pragma Assert(I = 98);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 2);
pragma Assert(Ctl_Type = 12);
Data_Len := J'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,J'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= J'Size/8);
pragma Assert(J = 95);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 3);
pragma Assert(Ctl_Type = 13);
Data_Len := K'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,K'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= K'Size/8);
pragma Assert(K = 23);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 4);
pragma Assert(Ctl_Type = 14);
Data_Len := L'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,L'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= L'Size/8);
pragma Assert(L = 29);
Put_Line("Offset =" & uint64_t'Image(Offset));
pragma Assert(Offset = Ctl_Len);
-- There should be no next message
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(not Received);
-- This should faile due to small buffer size
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf(1..12),Ctl_Len,1,11,I'Address,I'Size/8,Accepted);
pragma Assert(not Accepted);
-- Perform a networked test of the control message
Socketpair(PF_LOCAL,SOCK_STREAM,0,Fd1,Fd2,Error);
pragma Assert(Error = 0);
pragma Assert(Fd1 >= 0);
pragma Assert(Fd2 >= 0);
Fork(Child,Error);
pragma Assert(Error = 0);
if Child > 0 then
-- Child process
Close(Fd1,Error);
pragma Assert(Error = 0);
pragma Warnings(Off);
Fd1 := -1;
pragma Warnings(On);
declare
Data : String(1..32);
Iov : s_iovec_array := (
0 => ( iov_base => Data'Address, iov_len => Data'Length )
);
Msg : s_msghdr;
begin
Msg.msg_name := System.Null_Address;
Msg.msg_namelen := 0;
Msg.msg_iov := Iov'Address;
Msg.msg_iovlen := Iov'Length;
Msg.msg_control := Ctl_Buf'Address;
Msg.msg_controllen := Ctl_Buf'Length;
Msg.msg_flags := 0;
Recvmsg(Fd2,Msg,0,Error);
pragma Assert(Error = 0);
Offset := 0;
Len := Natural(Msg.msg_controllen);
Fd3 := -1;
Put_Line("Child: Read msg with controllen=" & Natural'Image(Len));
loop
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
exit when not Received;
Put_Line("Child: Read Level=" & int_t'Image(Ctl_Level) & ", Type=" & int_t'Image(Ctl_Type));
case Ctl_Level is
when SOL_SOCKET =>
Put_Line("Child: SOL_SOCKET");
case Ctl_Type is
when SCM_RIGHTS =>
Put_Line("Child: SCM_RIGHTS");
declare
Rights : fd_array_t(1..8);
Fd_Count : Natural := 0;
begin
Get_Cmsg(Ctl_Buf(1..Len),Offset,Rights,Fd_Count,Received);
pragma Assert(Error = 0);
Put_Line("Child: Count =" & Natural'Image(Fd_Count));
pragma Assert(Fd_Count = 1);
Fd3 := Rights(Rights'First);
Put_Line("Child: Fd3 =" & fd_t'Image(Fd3));
end;
when others =>
Put_Line("Child: SCM_OTHER");
null;
end case;
when others =>
Put_Line("Child: LEV_OTHER");
null;
end case;
end loop;
end;
Close(Fd3,Error);
pragma Assert(Error = 0); -- Success proves Fd came over to child proc
Close(Fd2,Error);
pragma Assert(Error = 0); -- Close socket
return;
end if;
-- Parent process
Close(Fd2,Error);
pragma Assert(Error = 0);
pragma Warnings(Off);
Fd2 := -1;
pragma Warnings(On);
-- Send File Descriptor to Child process
Open("Makefile",O_RDONLY,Fd3,Error);
pragma Assert(Error = 0);
pragma Assert(Fd3 >= 0);
declare
Fds : constant fd_array_t(1..1) := ( 1 => Fd3 );
begin
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf,Ctl_Len,Fds,Accepted);
pragma Assert(Accepted);
pragma Assert(Ctl_Len > 0);
end;
declare
Byte : String(1..1) := "X";
Iov : s_iovec_array := (
0 => ( iov_base => Byte'Address, iov_len => Byte'Length )
);
Msg : s_msghdr;
begin
Msg.msg_name := System.Null_Address;
Msg.msg_namelen := 0;
Msg.msg_iov := Iov'Address;
Msg.msg_iovlen := Iov'Length;
Msg.msg_control := Ctl_Buf'Address;
#if POSIX_FAMILY = "Linux"
Msg.msg_controllen := Ctl_Len;
#end if;
#if POSIX_FAMILY = "FreeBSD"
Msg.msg_controllen := uint_t(Ctl_Len);
#end if;
#if POSIX_FAMILY = "Darwin"
Msg.msg_controllen := uint_t(Ctl_Len);
#end if;
Msg.msg_flags := 0;
Sendmsg(Fd1,Msg,0,Error);
pragma Assert(Error = 0);
Put_Line("Parent sent msg..");
end;
Shutdown(Fd1,SHUT_RD,Error);
pragma Assert(Error = 0);
Put_Line("Parent SHUT_RD for " & fd_t'Image(Fd3));
Close(Fd3,Error);
pragma Assert(Error = 0);
Close(Fd1,Error);
pragma Assert(Error = 0);
-- Wait for child process to exit
declare
Status : int_t := -1;
begin
Wait_Pid(Child,0,Status,Error);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 0);
Put_Line("Child" & pid_t'Image(Child) & " exited with rc=" & int_t'Image(WEXITSTATUS(Status)));
end;
Put_Line("Test 0047 Passed.");
end T0047;
|
-- t0047.adb - Sat Feb 1 16:15:50 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- $Id$
--
-- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991
with Ada.Text_IO, System;
with Posix;
use Posix;
procedure T0047 is
use Ada.Text_IO;
I, J, L : int_t;
K : ushort_t;
Ctl_Buf : uchar_array(1..128);
Ctl_Len : uint64_t;
Len : Natural;
Ctl_Level : int_t;
Ctl_Type : int_t;
Offset : uint64_t;
Data_Len : uint64_t;
Accepted : Boolean;
Received : Boolean;
Fd1, Fd2 : fd_t := -1;
Fd3 : fd_t := -1;
Child : pid_t := -1;
Error : errno_t;
begin
Put_Line("Test 0047 - Put/Get_Cmsg");
I := 98;
J := 95;
K := 23;
L := 29;
-- Put control messages into Ctl_Buf
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf,Ctl_Len,1,11,I'Address,I'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,2,12,J'Address,J'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,3,13,K'Address,K'Size/8,Accepted);
pragma Assert(Accepted);
Put_Cmsg(Ctl_Buf,Ctl_Len,4,14,L'Address,L'Size/8,Accepted);
pragma Assert(Accepted);
pragma Assert(Ctl_Len > 8);
Put_Line("Ctl_Len =" & uint64_t'Image(Ctl_Len));
I := 0;
J := 0;
K := 0;
L := 0;
-- Get control messages back from Ctl_Buf
Offset := 0;
Len := Natural(Ctl_Len);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 1);
pragma Assert(Ctl_Type = 11);
Data_Len := I'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,I'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= I'Size/8);
pragma Assert(I = 98);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 2);
pragma Assert(Ctl_Type = 12);
Data_Len := J'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,J'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= J'Size/8);
pragma Assert(J = 95);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 3);
pragma Assert(Ctl_Type = 13);
Data_Len := K'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,K'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= K'Size/8);
pragma Assert(K = 23);
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(Received);
pragma Assert(Ctl_Level = 4);
pragma Assert(Ctl_Type = 14);
Data_Len := L'Size/8;
Get_Cmsg(Ctl_Buf(1..Len),Offset,L'Address,Data_Len,Received);
pragma Assert(Received);
pragma Assert(Data_Len >= L'Size/8);
pragma Assert(L = 29);
Put_Line("Offset =" & uint64_t'Image(Offset));
pragma Assert(Offset = Ctl_Len);
-- There should be no next message
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
pragma Assert(not Received);
-- This should faile due to small buffer size
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf(1..12),Ctl_Len,1,11,I'Address,I'Size/8,Accepted);
pragma Assert(not Accepted);
-- Perform a networked test of the control message
Socketpair(PF_LOCAL,SOCK_STREAM,0,Fd1,Fd2,Error);
pragma Assert(Error = 0);
pragma Assert(Fd1 >= 0);
pragma Assert(Fd2 >= 0);
Fork(Child,Error);
pragma Assert(Error = 0);
if Child > 0 then
-- Child process
Close(Fd1,Error);
pragma Assert(Error = 0);
pragma Warnings(Off);
Fd1 := -1;
pragma Warnings(On);
declare
Data : String(1..32);
Iov : s_iovec_array := (
0 => ( iov_base => Data'Address, iov_len => Data'Length )
);
Msg : s_msghdr;
begin
Msg.msg_name := System.Null_Address;
Msg.msg_namelen := 0;
Msg.msg_iov := Iov'Address;
Msg.msg_iovlen := Iov'Length;
Msg.msg_control := Ctl_Buf'Address;
Msg.msg_controllen := Ctl_Buf'Length;
Msg.msg_flags := 0;
Recvmsg(Fd2,Msg,0,Error);
pragma Assert(Error = 0);
Offset := 0;
Len := Natural(Msg.msg_controllen);
Fd3 := -1;
loop
Get_Cmsg(Ctl_Buf(1..Len),Offset,Ctl_Level,Ctl_Type,Received);
exit when not Received;
case Ctl_Level is
when SOL_SOCKET =>
case Ctl_Type is
when SCM_RIGHTS =>
declare
Rights : fd_array_t(1..8);
Fd_Count : Natural := 0;
begin
Get_Cmsg(Ctl_Buf(1..Len),Offset,Rights,Fd_Count,Received);
pragma Assert(Error = 0);
pragma Assert(Fd_Count = 1);
Fd3 := Rights(Rights'First);
end;
when others =>
null;
end case;
when others =>
null;
end case;
end loop;
end;
Close(Fd3,Error);
pragma Assert(Error = 0); -- Success proves Fd came over to child proc
Close(Fd2,Error);
pragma Assert(Error = 0); -- Close socket
return;
end if;
-- Parent process
Close(Fd2,Error);
pragma Assert(Error = 0);
pragma Warnings(Off);
Fd2 := -1;
pragma Warnings(On);
-- Send File Descriptor to Child process
Open("Makefile",O_RDONLY,Fd3,Error);
pragma Assert(Error = 0);
pragma Assert(Fd3 >= 0);
declare
Fds : constant fd_array_t(1..1) := ( 1 => Fd3 );
begin
Ctl_Len := 0;
Put_Cmsg(Ctl_Buf,Ctl_Len,Fds,Accepted);
pragma Assert(Accepted);
pragma Assert(Ctl_Len > 0);
end;
declare
Byte : String(1..1) := "X";
Iov : s_iovec_array := (
0 => ( iov_base => Byte'Address, iov_len => Byte'Length )
);
Msg : s_msghdr;
begin
Msg.msg_name := System.Null_Address;
Msg.msg_namelen := 0;
Msg.msg_iov := Iov'Address;
Msg.msg_iovlen := Iov'Length;
Msg.msg_control := Ctl_Buf'Address;
#if POSIX_FAMILY = "Linux"
Msg.msg_controllen := Ctl_Len;
#end if;
#if POSIX_FAMILY = "FreeBSD"
Msg.msg_controllen := uint_t(Ctl_Len);
#end if;
#if POSIX_FAMILY = "Darwin"
Msg.msg_controllen := uint_t(Ctl_Len);
#end if;
Msg.msg_flags := 0;
Sendmsg(Fd1,Msg,0,Error);
pragma Assert(Error = 0);
end;
Shutdown(Fd1,SHUT_RD,Error);
pragma Assert(Error = 0);
Close(Fd3,Error);
pragma Assert(Error = 0);
Close(Fd1,Error);
pragma Assert(Error = 0);
-- Wait for child process to exit
declare
Status : int_t := -1;
begin
Wait_Pid(Child,0,Status,Error);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 0);
end;
Put_Line("Test 0047 Passed.");
end T0047;
|
Test 47 finalized and cleaned up
|
Test 47 finalized and cleaned up
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
020c4c33f61e57e72e40171d770212dfc9d3991d
|
t0048.adb
|
t0048.adb
|
-- t0048.adb - Thu Feb 20 16:54:37 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- $Id$
--
-- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991
with Ada.Text_IO;
with Posix;
use Posix;
with System;
use System;
procedure T0048 is
use Ada.Text_IO;
Connect_Addr : constant String := "127.0.0.1";
Inet_C_Addr : s_sockaddr_in;
Port_C_No : constant ushort_t := 19199;
S, L : fd_t := -1; -- Connecting socket
Child : pid_t := -1;
Error : errno_t;
begin
Put_Line("Test 0048 - IPv4 socket/connect/etc.");
Fork(Child,Error);
pragma Assert(Error = 0);
if Child /= 0 then
-- Parent process
-- Create socket:
Socket(PF_INET,SOCK_STREAM,0,S,Error);
pragma Assert(Error = 0);
pragma Assert(S >= 0);
-- Create address to connect with:
Inet_C_Addr.sin_family := AF_INET;
Inet_C_Addr.sin_port := Htons(Port_C_No);
Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error);
pragma Assert(Error = 0);
-- Test Inet_Ntop -- should return same IPv4 String
declare
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Inet_Ntop(Inet_C_Addr.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
pragma Assert(Str_Addr(1..Last) = Connect_Addr);
end;
-- Test port
declare
Test_Port : constant ushort_t := Ntohs(Inet_C_Addr.sin_port);
begin
pragma Assert(Test_Port = Port_C_No);
null;
end;
-- Wait for client to setup and listen
Sleep(2);
-- Connect to the client process
Connect(S,Inet_C_Addr,Error);
pragma Assert(Error = 0);
-- Write something
declare
Msg : constant uchar_array := To_uchar_array("Hello!");
Count : Natural;
begin
Write(S,uchar_array(Msg),Count,Error);
pragma Assert(Error = 0);
pragma Assert(Count = Msg'Length);
end;
-- Close the socket
Close(S,Error);
pragma Assert(Error = 0);
-- Wait for child process to exit
declare
Status : int_t := -1;
begin
Wait_Pid(Child,0,Status,Error);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 0);
end;
Put_Line("Test 0048 Passed.");
else
-- Child process
-- Create a listening socket:
Socket(PF_INET,SOCK_STREAM,0,L,Error);
pragma Assert(Error = 0);
pragma Assert(L >= 0);
-- Create the address to bind to:
Inet_C_Addr.sin_family := AF_INET;
Inet_C_Addr.sin_port := Htons(Port_C_No);
Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error);
pragma Assert(Error = 0);
-- Bind to the address:
Bind(L,Inet_C_Addr,Error);
pragma Assert(Error = 0);
loop
Listen(L,10,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
-- Accept one connect
declare
Peer : u_sockaddr;
Peer_Len : socklen_t;
begin
loop
Accept_Connect(L,Peer,Peer_Len,S,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
pragma Assert(S >= 0);
pragma Assert(Peer.addr_sock.sa_family = AF_INET);
-- Display local socket address
declare
Local_Addr : u_sockaddr;
Addr_Len : socklen_t;
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Getsockname(S,Local_Addr,Addr_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Local_Addr.addr_sock.sa_family = AF_INET);
Inet_Ntop(Local_Addr.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Local name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Local_Addr.addr_in.sin_port)));
end;
-- Display peer's address
declare
Str_Addr : String(1..300);
Last : Natural := 0;
Port : constant ushort_t := Ntohs(Peer.addr_in.sin_port);
begin
Inet_Ntop(Peer.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port));
-- Test Getpeername
declare
Peer_Name : u_sockaddr;
Name_Len : socklen_t;
Buf2 : String(1..300);
Last2 : Natural := 0;
begin
Getpeername(S,Peer_Name,Name_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Peer_Name.addr_sock.sa_family = AF_INET);
Inet_Ntop(Peer_Name.addr_in.sin_addr,Buf2,Last2,Error);
pragma Assert(Error = 0);
pragma Assert(Buf2(1..Last2) = Str_Addr(1..Last));
Put_Line("Peer name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Peer_Name.addr_in.sin_port)));
end;
end;
end;
#if POSIX_FAMILY = "FreeBSD" or POSIX_FAMILY = "Darwin"
-- Test KQueue
declare
Kq : fd_t;
Chgs : s_kevent_array(1..1);
Evts : s_kevent_array(1..1);
N_Evts : Natural := 0;
Timeout : constant s_timespec := ( tv_sec => 1, tv_nsec => 0 );
begin
KQueue(Kq,Error);
pragma Assert(Kq >= 0);
Chgs(1).ident := uint64_t(S);
Chgs(1).filter := EVFILT_READ;
Chgs(1).flags := EV_ADD;
Chgs(1).fflags := 0;
Chgs(1).udata := Null_Address;
loop
KEvent(Kq,Chgs,1,Timeout,Evts,N_Evts,Error);
pragma assert(Error = 0);
exit when N_Evts > 0;
end loop;
pragma Assert(N_Evts > 0);
pragma Assert(Evts(1).ident = uint64_t(S));
pragma Assert(Evts(1).filter = EVFILT_READ);
pragma Assert(Evts(1).data > 0);
pragma Assert(Evts(1).udata = Null_Address);
declare
Rx_Avail : constant Natural := Natural(Evts(1).data);
Rx_Buf : uchar_array(1..Rx_Avail);
Last : Natural;
begin
Read(S,Rx_Buf,Last,Error);
pragma Assert(Error = 0);
pragma Assert(Last = Rx_Avail);
Put("Got msg '");
Put(To_String(Rx_Buf(1..Last)));
Put_Line("'");
end;
Close(Kq,Error);
pragma Assert(Error = 0);
end;
#end if;
-- Close listening socket
Close(L,Error);
pragma Assert(Error = 0);
-- Test getsockopt(2)
declare
Sock_Error : int_t := -33;
Keep_Alive : int_t := -33;
begin
Get_Sockopt(S,SOL_SOCKET,SO_ERROR,Sock_Error,Error);
pragma Assert(Error = 0);
pragma Assert(Sock_Error = 0);
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive >= 0);
if Keep_Alive /= 0 then
Keep_Alive := 0; -- Turn it off
Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
Keep_Alive := -95;
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive = 0);
else
Keep_Alive := 1; -- Turn it on
Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
Keep_Alive := -95;
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive /= 0);
end if;
end;
declare
Linger : s_linger := ( l_onoff => 1, l_linger => 2 );
begin
Set_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
Linger.l_onoff := 0;
Linger.l_linger := 23;
Get_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
pragma Assert(Linger.l_onoff /= 0);
pragma Assert(Linger.l_linger = 2);
end;
-- Close accepted socket
Close(S,Error);
pragma Assert(Error = 0);
end if;
end T0048;
|
-- t0048.adb - Thu Feb 20 16:54:37 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- $Id$
--
-- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991
with Ada.Text_IO;
with Posix;
use Posix;
with System;
use System;
procedure T0048 is
use Ada.Text_IO;
Connect_Addr : constant String := "127.0.0.1";
Inet_C_Addr : s_sockaddr_in;
Port_C_No : constant ushort_t := 19199;
S, L : fd_t := -1; -- Connecting socket
Child : pid_t := -1;
Error : errno_t;
begin
Put_Line("Test 0048 - IPv4 socket/connect/etc.");
Fork(Child,Error);
pragma Assert(Error = 0);
if Child /= 0 then
-- Parent process
-- Create socket:
Socket(PF_INET,SOCK_STREAM,0,S,Error);
pragma Assert(Error = 0);
pragma Assert(S >= 0);
-- Create address to connect with:
Inet_C_Addr.sin_family := AF_INET;
Inet_C_Addr.sin_port := Htons(Port_C_No);
Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error);
pragma Assert(Error = 0);
-- Test Inet_Ntop -- should return same IPv4 String
declare
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Inet_Ntop(Inet_C_Addr.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
pragma Assert(Str_Addr(1..Last) = Connect_Addr);
end;
-- Test port
declare
Test_Port : constant ushort_t := Ntohs(Inet_C_Addr.sin_port);
begin
pragma Assert(Test_Port = Port_C_No);
null;
end;
-- Wait for client to setup and listen
Sleep(2);
-- Connect to the client process
Connect(S,Inet_C_Addr,Error);
pragma Assert(Error = 0);
-- Write something
declare
Msg : constant uchar_array := To_uchar_array("Hello!");
Count : Natural;
begin
Write(S,uchar_array(Msg),Count,Error);
pragma Assert(Error = 0);
pragma Assert(Count = Msg'Length);
end;
-- Test Shutdown(2)
Shutdown(S,SHUT_RD,Error);
pragma Assert(Error = 0);
-- Close the socket
Close(S,Error);
pragma Assert(Error = 0);
-- Wait for child process to exit
declare
Status : int_t := -1;
begin
Wait_Pid(Child,0,Status,Error);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 0);
end;
Put_Line("Test 0048 Passed.");
else
-- Child process
-- Create a listening socket:
Socket(PF_INET,SOCK_STREAM,0,L,Error);
pragma Assert(Error = 0);
pragma Assert(L >= 0);
-- Create the address to bind to:
Inet_C_Addr.sin_family := AF_INET;
Inet_C_Addr.sin_port := Htons(Port_C_No);
Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error);
pragma Assert(Error = 0);
-- Bind to the address:
Bind(L,Inet_C_Addr,Error);
pragma Assert(Error = 0);
loop
Listen(L,10,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
-- Accept one connect
declare
Peer : u_sockaddr;
Peer_Len : socklen_t;
begin
loop
Accept_Connect(L,Peer,Peer_Len,S,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
pragma Assert(S >= 0);
pragma Assert(Peer.addr_sock.sa_family = AF_INET);
-- Display local socket address
declare
Local_Addr : u_sockaddr;
Addr_Len : socklen_t;
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Getsockname(S,Local_Addr,Addr_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Local_Addr.addr_sock.sa_family = AF_INET);
Inet_Ntop(Local_Addr.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Local name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Local_Addr.addr_in.sin_port)));
end;
-- Display peer's address
declare
Str_Addr : String(1..300);
Last : Natural := 0;
Port : constant ushort_t := Ntohs(Peer.addr_in.sin_port);
begin
Inet_Ntop(Peer.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port));
-- Test Getpeername
declare
Peer_Name : u_sockaddr;
Name_Len : socklen_t;
Buf2 : String(1..300);
Last2 : Natural := 0;
begin
Getpeername(S,Peer_Name,Name_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Peer_Name.addr_sock.sa_family = AF_INET);
Inet_Ntop(Peer_Name.addr_in.sin_addr,Buf2,Last2,Error);
pragma Assert(Error = 0);
pragma Assert(Buf2(1..Last2) = Str_Addr(1..Last));
Put_Line("Peer name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Peer_Name.addr_in.sin_port)));
end;
end;
end;
#if POSIX_FAMILY = "FreeBSD" or POSIX_FAMILY = "Darwin"
-- Test KQueue
declare
Kq : fd_t;
Chgs : s_kevent_array(1..1);
Evts : s_kevent_array(1..1);
N_Evts : Natural := 0;
Timeout : constant s_timespec := ( tv_sec => 1, tv_nsec => 0 );
begin
KQueue(Kq,Error);
pragma Assert(Kq >= 0);
Chgs(1).ident := uint64_t(S);
Chgs(1).filter := EVFILT_READ;
Chgs(1).flags := EV_ADD;
Chgs(1).fflags := 0;
Chgs(1).udata := Null_Address;
loop
KEvent(Kq,Chgs,1,Timeout,Evts,N_Evts,Error);
pragma assert(Error = 0);
exit when N_Evts > 0;
end loop;
pragma Assert(N_Evts > 0);
pragma Assert(Evts(1).ident = uint64_t(S));
pragma Assert(Evts(1).filter = EVFILT_READ);
pragma Assert(Evts(1).data > 0);
pragma Assert(Evts(1).udata = Null_Address);
declare
Rx_Avail : constant Natural := Natural(Evts(1).data);
Rx_Buf : uchar_array(1..Rx_Avail);
Last : Natural;
begin
Read(S,Rx_Buf,Last,Error);
pragma Assert(Error = 0);
pragma Assert(Last = Rx_Avail);
Put("Got msg '");
Put(To_String(Rx_Buf(1..Last)));
Put_Line("'");
end;
Close(Kq,Error);
pragma Assert(Error = 0);
end;
#end if;
-- Close listening socket
Close(L,Error);
pragma Assert(Error = 0);
-- Test getsockopt(2)
declare
Sock_Error : int_t := -33;
Keep_Alive : int_t := -33;
begin
Get_Sockopt(S,SOL_SOCKET,SO_ERROR,Sock_Error,Error);
pragma Assert(Error = 0);
pragma Assert(Sock_Error = 0);
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive >= 0);
if Keep_Alive /= 0 then
Keep_Alive := 0; -- Turn it off
Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
Keep_Alive := -95;
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive = 0);
else
Keep_Alive := 1; -- Turn it on
Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
Keep_Alive := -95;
Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error);
pragma Assert(Error = 0);
pragma Assert(Keep_Alive /= 0);
end if;
end;
declare
Linger : s_linger := ( l_onoff => 1, l_linger => 2 );
begin
Set_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
Linger.l_onoff := 0;
Linger.l_linger := 23;
Get_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
pragma Assert(Linger.l_onoff /= 0);
pragma Assert(Linger.l_linger = 2);
end;
-- Close accepted socket
Close(S,Error);
pragma Assert(Error = 0);
end if;
end T0048;
|
Test Shutdown()
|
Test Shutdown()
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
64ed460fc7e96a55991ac1c34e9a0bb5578c2b9e
|
src/asf-lifecycles-response.ads
|
src/asf-lifecycles-response.ads
|
-----------------------------------------------------------------------
-- asf-lifecycles-response -- Response phase
-- 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.
-----------------------------------------------------------------------
-- The <b>ASF.Lifecycles.Response</b> package defines the behavior
-- of the response phase.
with ASF.Applications.Views;
package ASF.Lifecycles.Response is
-- ------------------------------
-- Response controller
-- ------------------------------
type Response_Controller is new Phase_Controller with private;
-- Initialize the phase controller.
overriding
procedure Initialize (Controller : in out Response_Controller;
App : access ASF.Applications.Main.Application'Class);
-- Execute the restore view phase.
overriding
procedure Execute (Controller : in Response_Controller;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
private
type Response_Controller is new Phase_Controller with record
View_Handler : access ASF.Applications.Views.View_Handler'Class;
end record;
end ASF.Lifecycles.Response;
|
-----------------------------------------------------------------------
-- asf-lifecycles-response -- Response phase
-- Copyright (C) 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Lifecycles.Response</b> package defines the behavior
-- of the response phase.
with ASF.Applications.Views;
package ASF.Lifecycles.Response is
-- ------------------------------
-- Response controller
-- ------------------------------
type Response_Controller is new Phase_Controller with private;
-- Initialize the phase controller.
overriding
procedure Initialize (Controller : in out Response_Controller;
Views : access ASF.Applications.Views.View_Handler'Class);
-- Execute the restore view phase.
overriding
procedure Execute (Controller : in Response_Controller;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
private
type Response_Controller is new Phase_Controller with record
View_Handler : access ASF.Applications.Views.View_Handler'Class;
end record;
end ASF.Lifecycles.Response;
|
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
|
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bfb72816c13091890111429a8ef98163c67c7bb9
|
src/natools-smaz_generic.ads
|
src/natools-smaz_generic.ads
|
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
with Ada.Streams;
generic
type Dictionary_Code is (<>);
with procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Dictionary_Code;
Verbatim_Length : out Natural;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean);
with procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String);
with procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive);
with function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count;
with procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Dictionary_Code);
with procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean);
package Natools.Smaz_Generic is
pragma Pure;
type Offset_Array is array (Dictionary_Code range <>) of Positive;
type Dictionary
(Last_Code : Dictionary_Code;
Values_Last : Natural)
is record
Variable_Length_Verbatim : Boolean;
Max_Word_Length : Positive;
Offsets : Offset_Array
(Dictionary_Code'Succ (Dictionary_Code'First) .. Last_Code);
Values : String (1 .. Values_Last);
Hash : not null access function (Value : String) return Natural;
end record;
function Code_First
(Offsets : in Offset_Array;
Code : in Dictionary_Code;
Fallback : in Positive)
return Positive
is (if Code in Offsets'Range then Offsets (Code) else Fallback);
-- Return the first index of the value for Code in Dictionary.Values
function Code_Last
(Offsets : in Offset_Array;
Code : in Dictionary_Code;
Fallback : in Natural)
return Natural
is (if Dictionary_Code'Succ (Code) in Offsets'Range
then Offsets (Dictionary_Code'Succ (Code)) - 1
else Fallback);
-- Return the value index of the value for Code in Dictionary.Values
function Is_Valid_Code
(Dict : in Dictionary;
Code : in Dictionary_Code)
return Boolean
is (Code in Dictionary_Code'First .. Dict.Last_Code);
-- Return whether Code exists in Dict
function Dict_Entry
(Dict : in Dictionary;
Code : in Dictionary_Code)
return String
is (Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First)
.. Code_Last (Dict.Offsets, Code, Dict.Values'Last)))
with Pre => Is_Valid_Code (Dict, Code);
-- Return the string for at the given Index in Dict
function Dict_Entry_Length
(Dict : in Dictionary;
Code : in Dictionary_Code)
return Positive
is (1 + Code_Last (Dict.Offsets, Code, Dict.Values'Last)
- Code_First (Dict.Offsets, Code, Dict.Values'First))
with Pre => Is_Valid_Code (Dict, Code);
-- Return the length of the string for at the given Index in Dict
function Is_Valid (Dictionary : in Smaz_Generic.Dictionary) return Boolean
is ((for all Code in Dictionary.Offsets'Range
=> Dictionary.Offsets (Code) in Dictionary.Values'Range)
and then (for all Code in Dictionary_Code'First .. Dictionary.Last_Code
=> Code_Last (Dictionary.Offsets, Code, Dictionary.Values'Last) + 1
- Code_First (Dictionary.Offsets, Code, Dictionary.Values'First)
in 1 .. Dictionary.Max_Word_Length)
and then (for all Code in Dictionary_Code'First .. Dictionary.Last_Code
=> Dictionary_Code'Val (Dictionary.Hash
(Dict_Entry (Dictionary, Code)))
= Code));
-- Check all the assumptions made on Dictionary objects.
function Compressed_Upper_Bound
(Dict : in Dictionary;
Input : in String)
return Ada.Streams.Stream_Element_Count;
-- Return the maximum number of bytes needed to encode Input
procedure Compress
(Dict : in Dictionary;
Input : in String;
Output_Buffer : out Ada.Streams.Stream_Element_Array;
Output_Last : out Ada.Streams.Stream_Element_Offset);
-- Encode Input into Output_Buffer
function Compress (Dict : in Dictionary; Input : in String)
return Ada.Streams.Stream_Element_Array;
-- Return an encoded buffer for Input
function Decompressed_Length
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array)
return Natural;
-- Return the exact length when Input is decoded
procedure Decompress
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array;
Output_Buffer : out String;
Output_Last : out Natural);
-- Decode Input into Output_Buffer
function Decompress
(Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array)
return String;
-- Return a decoded buffer for Input
end Natools.Smaz_Generic;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Smaz_Generic provides a generic implementation of the Smaz --
-- algorithm, leaving encoding and decoding to the formal subprograms. --
-- This factors all the logic common to standard byte-based Smaz, the --
-- the base-64 variant, and the base-4096 variant. --
-- --
-- WARNING: an important assumption that is not checked/asserted, is that --
-- it is never preferable to use verbatim encoding rather than a code, --
-- except when merging to verbatim sections and the code between them. This --
-- means in particular that a dictionary must never contain an entry --
-- shorter than its encoded counterpart. --
------------------------------------------------------------------------------
with Ada.Streams;
generic
type Dictionary_Code is (<>);
with procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Dictionary_Code;
Verbatim_Length : out Natural;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean);
with procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String);
with procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive);
with function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count;
with procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Dictionary_Code);
with procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Dictionary_Code;
Variable_Length_Verbatim : in Boolean);
package Natools.Smaz_Generic is
pragma Pure;
type Offset_Array is array (Dictionary_Code range <>) of Positive;
type Dictionary
(Last_Code : Dictionary_Code;
Values_Last : Natural)
is record
Variable_Length_Verbatim : Boolean;
Max_Word_Length : Positive;
Offsets : Offset_Array
(Dictionary_Code'Succ (Dictionary_Code'First) .. Last_Code);
Values : String (1 .. Values_Last);
Hash : not null access function (Value : String) return Natural;
end record;
function Code_First
(Offsets : in Offset_Array;
Code : in Dictionary_Code;
Fallback : in Positive)
return Positive
is (if Code in Offsets'Range then Offsets (Code) else Fallback);
-- Return the first index of the value for Code in Dictionary.Values
function Code_Last
(Offsets : in Offset_Array;
Code : in Dictionary_Code;
Fallback : in Natural)
return Natural
is (if Dictionary_Code'Succ (Code) in Offsets'Range
then Offsets (Dictionary_Code'Succ (Code)) - 1
else Fallback);
-- Return the value index of the value for Code in Dictionary.Values
function Is_Valid_Code
(Dict : in Dictionary;
Code : in Dictionary_Code)
return Boolean
is (Code in Dictionary_Code'First .. Dict.Last_Code);
-- Return whether Code exists in Dict
function Dict_Entry
(Dict : in Dictionary;
Code : in Dictionary_Code)
return String
is (Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First)
.. Code_Last (Dict.Offsets, Code, Dict.Values'Last)))
with Pre => Is_Valid_Code (Dict, Code);
-- Return the string for at the given Index in Dict
function Dict_Entry_Length
(Dict : in Dictionary;
Code : in Dictionary_Code)
return Positive
is (1 + Code_Last (Dict.Offsets, Code, Dict.Values'Last)
- Code_First (Dict.Offsets, Code, Dict.Values'First))
with Pre => Is_Valid_Code (Dict, Code);
-- Return the length of the string for at the given Index in Dict
function Is_Valid (Dictionary : in Smaz_Generic.Dictionary) return Boolean
is ((for all Code in Dictionary.Offsets'Range
=> Dictionary.Offsets (Code) in Dictionary.Values'Range)
and then (for all Code in Dictionary_Code'First .. Dictionary.Last_Code
=> Code_Last (Dictionary.Offsets, Code, Dictionary.Values'Last) + 1
- Code_First (Dictionary.Offsets, Code, Dictionary.Values'First)
in 1 .. Dictionary.Max_Word_Length)
and then (for all Code in Dictionary_Code'First .. Dictionary.Last_Code
=> Dictionary_Code'Val (Dictionary.Hash
(Dict_Entry (Dictionary, Code)))
= Code));
-- Check all the assumptions made on Dictionary objects.
function Compressed_Upper_Bound
(Dict : in Dictionary;
Input : in String)
return Ada.Streams.Stream_Element_Count;
-- Return the maximum number of bytes needed to encode Input
procedure Compress
(Dict : in Dictionary;
Input : in String;
Output_Buffer : out Ada.Streams.Stream_Element_Array;
Output_Last : out Ada.Streams.Stream_Element_Offset);
-- Encode Input into Output_Buffer
function Compress (Dict : in Dictionary; Input : in String)
return Ada.Streams.Stream_Element_Array;
-- Return an encoded buffer for Input
function Decompressed_Length
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array)
return Natural;
-- Return the exact length when Input is decoded
procedure Decompress
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array;
Output_Buffer : out String;
Output_Last : out Natural);
-- Decode Input into Output_Buffer
function Decompress
(Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array)
return String;
-- Return a decoded buffer for Input
end Natools.Smaz_Generic;
|
add a description and an important warning
|
smaz_generic: add a description and an important warning
|
Ada
|
isc
|
faelys/natools
|
f1cdaa169bb5027ea12281418d1b66e5c072f3d7
|
samples/popen.adb
|
samples/popen.adb
|
-----------------------------------------------------------------------
-- pipe -- Print the GNAT version by using a pipe
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
procedure Popen is
Command : constant String := "gnatmake --version";
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (Pipe'Unchecked_Access, 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
return;
end if;
Ada.Text_IO.Put_Line ("Result: " & Ada.Strings.Unbounded.To_String (Content));
end Popen;
|
-----------------------------------------------------------------------
-- pipe -- Print the GNAT version by using a pipe
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
procedure Popen is
Command : constant String := "gnatmake --version";
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (Pipe'Access, 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
return;
end if;
Ada.Text_IO.Put_Line ("Result: " & Ada.Strings.Unbounded.To_String (Content));
end Popen;
|
Replace Unchecked_Access by Access in stream initialization
|
Replace Unchecked_Access by Access in stream initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4ed5ae4476bffc1914865c6ea253165b4e4e7577
|
ARM/STMicro/STM32/drivers/stm32f4.ads
|
ARM/STMicro/STM32/drivers/stm32f4.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This file provides type definitions for the STM32F4 (ARM Cortex M4F)
-- microcontrollers from ST Microelectronics.
with Interfaces;
with System.Storage_Elements;
use System;
use type System.Storage_Elements.Storage_Offset;
package STM32F4 is
type Word is new Interfaces.Unsigned_32; -- for shift/rotate
type Half_Word is new Interfaces.Unsigned_16; -- for shift/rotate
type Byte is new Interfaces.Unsigned_8; -- for shift/rotate
type Bits_1 is mod 2**1 with Size => 1;
type Bits_2 is mod 2**2 with Size => 2;
type Bits_3 is mod 2**3 with Size => 3;
type Bits_4 is mod 2**4 with Size => 4;
type Bits_5 is mod 2**5 with Size => 5;
type Bits_6 is mod 2**6 with Size => 6;
type Bits_7 is mod 2**7 with Size => 7;
type Bits_8 is mod 2**8 with Size => 8;
type Bits_9 is mod 2**9 with Size => 9;
type Bits_10 is mod 2**10 with Size => 10;
type Bits_11 is mod 2**11 with Size => 11;
type Bits_12 is mod 2**12 with Size => 12;
type Bits_13 is mod 2**13 with Size => 13;
type Bits_14 is mod 2**14 with Size => 14;
type Bits_15 is mod 2**15 with Size => 15;
type Bits_16 is mod 2**16 with Size => 16;
type Bits_17 is mod 2**17 with Size => 17;
type Bits_18 is mod 2**18 with Size => 18;
type Bits_19 is mod 2**19 with Size => 19;
type Bits_20 is mod 2**20 with Size => 20;
type Bits_21 is mod 2**21 with Size => 21;
type Bits_22 is mod 2**22 with Size => 22;
type Bits_23 is mod 2**23 with Size => 23;
type Bits_24 is mod 2**24 with Size => 24;
type Bits_25 is mod 2**25 with Size => 25;
type Bits_26 is mod 2**26 with Size => 26;
type Bits_27 is mod 2**27 with Size => 27;
type Bits_28 is mod 2**28 with Size => 28;
type Bits_29 is mod 2**29 with Size => 29;
type Bits_30 is mod 2**30 with Size => 30;
type Bits_32x1 is array (0 .. 31) of Bits_1 with Size => 32;
type Bits_16x2 is array (0 .. 15) of Bits_2 with Size => 32;
type Bits_8x4 is array (0 .. 7) of Bits_4 with Size => 32;
-- Define address bases for the various system components
Peripheral_Base : constant Address := System'To_Address (16#4000_0000#);
APB1_Peripheral_Base : constant Address := Peripheral_Base;
APB2_Peripheral_Base : constant Address := Peripheral_Base + 16#0001_0000#;
AHB1_Peripheral_Base : constant Address := Peripheral_Base + 16#0002_0000#;
AHB2_Peripheral_Base : constant Address := Peripheral_Base + 16#1000_0000#;
GPIOA_Base : constant Address := AHB1_Peripheral_Base + 16#0000#;
GPIOB_Base : constant Address := AHB1_Peripheral_Base + 16#0400#;
GPIOC_Base : constant Address := AHB1_Peripheral_Base + 16#0800#;
GPIOD_Base : constant Address := AHB1_Peripheral_Base + 16#0C00#;
GPIOE_Base : constant Address := AHB1_Peripheral_Base + 16#1000#;
GPIOF_Base : constant Address := AHB1_Peripheral_Base + 16#1400#;
GPIOG_Base : constant Address := AHB1_Peripheral_Base + 16#1800#;
GPIOH_Base : constant Address := AHB1_Peripheral_Base + 16#1C00#;
GPIOI_Base : constant Address := AHB1_Peripheral_Base + 16#2000#;
GPIOJ_Base : constant Address := AHB1_Peripheral_Base + 16#2400#;
GPIOK_Base : constant Address := AHB1_Peripheral_Base + 16#2800#;
RCC_Base : constant Address := AHB1_Peripheral_Base + 16#3800#;
FLASH_Base : constant Address := AHB1_Peripheral_Base + 16#3C00#;
DMA1_Base : constant Address := AHB1_Peripheral_Base + 16#6000#;
DMA2_Base : constant Address := AHB1_Peripheral_Base + 16#6400#;
ETH_Base : constant Address := AHB1_Peripheral_Base + 16#8000#;
ETH_MAC_Base : constant Address := ETH_Base;
ETH_MMC_Base : constant Address := ETH_Base + 16#0100#;
ETH_PTP_Base : constant Address := ETH_Base + 16#0700#;
ETH_DMA_Base : constant Address := ETH_Base + 16#1000#;
DMA2D_BASE : constant Address := AHB1_Peripheral_Base + 16#B000#;
RNG_BASE : constant Address := AHB2_Peripheral_Base + 16#6_0800#;
TIM2_Base : constant Address := APB1_Peripheral_Base + 16#0000#;
TIM3_Base : constant Address := APB1_Peripheral_Base + 16#0400#;
TIM4_Base : constant Address := APB1_Peripheral_Base + 16#0800#;
TIM5_Base : constant Address := APB1_Peripheral_Base + 16#0C00#;
TIM6_Base : constant Address := APB1_Peripheral_Base + 16#1000#;
TIM7_Base : constant Address := APB1_Peripheral_Base + 16#1400#;
TIM12_Base : constant Address := APB1_Peripheral_Base + 16#1800#;
TIM13_Base : constant Address := APB1_Peripheral_Base + 16#1C00#;
TIM14_Base : constant Address := APB1_Peripheral_Base + 16#2000#;
RTC_Base : constant Address := APB1_Peripheral_Base + 16#2800#;
WWDG_Base : constant Address := APB1_Peripheral_Base + 16#2C00#;
IWDG_Base : constant Address := APB1_Peripheral_Base + 16#3000#;
I2S2ext_Base : constant Address := APB1_Peripheral_Base + 16#3400#;
SPI2_Base : constant Address := APB1_Peripheral_Base + 16#3800#;
SPI3_Base : constant Address := APB1_Peripheral_Base + 16#3C00#;
I2S3ext_Base : constant Address := APB1_Peripheral_Base + 16#4000#;
USART2_Base : constant Address := APB1_Peripheral_Base + 16#4400#;
USART3_Base : constant Address := APB1_Peripheral_Base + 16#4800#;
UART4_Base : constant Address := APB1_Peripheral_Base + 16#4C00#;
UART5_Base : constant Address := APB1_Peripheral_Base + 16#5000#;
I2C1_Base : constant Address := APB1_Peripheral_Base + 16#5400#;
I2C2_Base : constant Address := APB1_Peripheral_Base + 16#5800#;
I2C3_Base : constant Address := APB1_Peripheral_Base + 16#5C00#;
CAN1_Base : constant Address := APB1_Peripheral_Base + 16#6400#;
CAN2_Base : constant Address := APB1_Peripheral_Base + 16#6800#;
PWR_Base : constant Address := APB1_Peripheral_Base + 16#7000#;
DAC_Base : constant Address := APB1_Peripheral_Base + 16#7400#;
UART7_BASE : constant Address := APB1_Peripheral_Base + 16#7800#;
UART8_BASE : constant Address := APB1_Peripheral_Base + 16#7C00#;
TIM1_Base : constant Address := APB2_Peripheral_Base + 16#0000#;
TIM8_Base : constant Address := APB2_Peripheral_Base + 16#0400#;
USART1_Base : constant Address := APB2_Peripheral_Base + 16#1000#;
USART6_Base : constant Address := APB2_Peripheral_Base + 16#1400#;
ADC1_Base : constant Address := APB2_Peripheral_Base + 16#2000#;
ADC2_Base : constant Address := APB2_Peripheral_Base + 16#2100#;
ADC3_Base : constant Address := APB2_Peripheral_Base + 16#2200#;
ADC_Base : constant Address := APB2_Peripheral_Base + 16#2300#;
SDIO_Base : constant Address := APB2_Peripheral_Base + 16#2C00#;
SPI1_Base : constant Address := APB2_Peripheral_Base + 16#3000#;
SPI4_BASE : constant Address := APB2_Peripheral_Base + 16#3400#;
SYSCFG_Base : constant Address := APB2_Peripheral_Base + 16#3800#;
EXTI_Base : constant Address := APB2_Peripheral_Base + 16#3C00#;
TIM9_Base : constant Address := APB2_Peripheral_Base + 16#4000#;
TIM10_Base : constant Address := APB2_Peripheral_Base + 16#4400#;
TIM11_Base : constant Address := APB2_Peripheral_Base + 16#4800#;
SPI5_BASE : constant Address := APB2_Peripheral_Base + 16#5000#;
SPI6_BASE : constant Address := APB2_Peripheral_Base + 16#5400#;
SAI1_BASE : constant Address := APB2_Peripheral_Base + 16#5800#;
LTDC_BASE : constant Address := APB2_Peripheral_Base + 16#6800#;
end STM32F4;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This file provides type definitions for the STM32F4 (ARM Cortex M4F)
-- microcontrollers from ST Microelectronics.
with Interfaces;
with System.Storage_Elements;
use System;
use type System.Storage_Elements.Storage_Offset;
package STM32F4 is
type Word is new Interfaces.Unsigned_32; -- for shift/rotate
type Half_Word is new Interfaces.Unsigned_16; -- for shift/rotate
type Byte is new Interfaces.Unsigned_8; -- for shift/rotate
type Bits_1 is mod 2**1 with Size => 1;
type Bits_2 is mod 2**2 with Size => 2;
type Bits_3 is mod 2**3 with Size => 3;
type Bits_4 is mod 2**4 with Size => 4;
type Bits_5 is mod 2**5 with Size => 5;
type Bits_6 is mod 2**6 with Size => 6;
type Bits_7 is mod 2**7 with Size => 7;
type Bits_8 is mod 2**8 with Size => 8;
type Bits_9 is mod 2**9 with Size => 9;
type Bits_10 is mod 2**10 with Size => 10;
type Bits_11 is mod 2**11 with Size => 11;
type Bits_12 is mod 2**12 with Size => 12;
type Bits_13 is mod 2**13 with Size => 13;
type Bits_14 is mod 2**14 with Size => 14;
type Bits_15 is mod 2**15 with Size => 15;
type Bits_16 is mod 2**16 with Size => 16;
type Bits_17 is mod 2**17 with Size => 17;
type Bits_18 is mod 2**18 with Size => 18;
type Bits_19 is mod 2**19 with Size => 19;
type Bits_20 is mod 2**20 with Size => 20;
type Bits_21 is mod 2**21 with Size => 21;
type Bits_22 is mod 2**22 with Size => 22;
type Bits_23 is mod 2**23 with Size => 23;
type Bits_24 is mod 2**24 with Size => 24;
type Bits_25 is mod 2**25 with Size => 25;
type Bits_26 is mod 2**26 with Size => 26;
type Bits_27 is mod 2**27 with Size => 27;
type Bits_28 is mod 2**28 with Size => 28;
type Bits_29 is mod 2**29 with Size => 29;
type Bits_30 is mod 2**30 with Size => 30;
type Bits_32x1 is array (0 .. 31) of Bits_1 with Pack, Size => 32;
type Bits_16x2 is array (0 .. 15) of Bits_2 with Pack, Size => 32;
type Bits_8x4 is array (0 .. 7) of Bits_4 with Pack, Size => 32;
-- Define address bases for the various system components
Peripheral_Base : constant Address := System'To_Address (16#4000_0000#);
APB1_Peripheral_Base : constant Address := Peripheral_Base;
APB2_Peripheral_Base : constant Address := Peripheral_Base + 16#0001_0000#;
AHB1_Peripheral_Base : constant Address := Peripheral_Base + 16#0002_0000#;
AHB2_Peripheral_Base : constant Address := Peripheral_Base + 16#1000_0000#;
GPIOA_Base : constant Address := AHB1_Peripheral_Base + 16#0000#;
GPIOB_Base : constant Address := AHB1_Peripheral_Base + 16#0400#;
GPIOC_Base : constant Address := AHB1_Peripheral_Base + 16#0800#;
GPIOD_Base : constant Address := AHB1_Peripheral_Base + 16#0C00#;
GPIOE_Base : constant Address := AHB1_Peripheral_Base + 16#1000#;
GPIOF_Base : constant Address := AHB1_Peripheral_Base + 16#1400#;
GPIOG_Base : constant Address := AHB1_Peripheral_Base + 16#1800#;
GPIOH_Base : constant Address := AHB1_Peripheral_Base + 16#1C00#;
GPIOI_Base : constant Address := AHB1_Peripheral_Base + 16#2000#;
GPIOJ_Base : constant Address := AHB1_Peripheral_Base + 16#2400#;
GPIOK_Base : constant Address := AHB1_Peripheral_Base + 16#2800#;
RCC_Base : constant Address := AHB1_Peripheral_Base + 16#3800#;
FLASH_Base : constant Address := AHB1_Peripheral_Base + 16#3C00#;
DMA1_Base : constant Address := AHB1_Peripheral_Base + 16#6000#;
DMA2_Base : constant Address := AHB1_Peripheral_Base + 16#6400#;
ETH_Base : constant Address := AHB1_Peripheral_Base + 16#8000#;
ETH_MAC_Base : constant Address := ETH_Base;
ETH_MMC_Base : constant Address := ETH_Base + 16#0100#;
ETH_PTP_Base : constant Address := ETH_Base + 16#0700#;
ETH_DMA_Base : constant Address := ETH_Base + 16#1000#;
DMA2D_BASE : constant Address := AHB1_Peripheral_Base + 16#B000#;
RNG_BASE : constant Address := AHB2_Peripheral_Base + 16#6_0800#;
TIM2_Base : constant Address := APB1_Peripheral_Base + 16#0000#;
TIM3_Base : constant Address := APB1_Peripheral_Base + 16#0400#;
TIM4_Base : constant Address := APB1_Peripheral_Base + 16#0800#;
TIM5_Base : constant Address := APB1_Peripheral_Base + 16#0C00#;
TIM6_Base : constant Address := APB1_Peripheral_Base + 16#1000#;
TIM7_Base : constant Address := APB1_Peripheral_Base + 16#1400#;
TIM12_Base : constant Address := APB1_Peripheral_Base + 16#1800#;
TIM13_Base : constant Address := APB1_Peripheral_Base + 16#1C00#;
TIM14_Base : constant Address := APB1_Peripheral_Base + 16#2000#;
RTC_Base : constant Address := APB1_Peripheral_Base + 16#2800#;
WWDG_Base : constant Address := APB1_Peripheral_Base + 16#2C00#;
IWDG_Base : constant Address := APB1_Peripheral_Base + 16#3000#;
I2S2ext_Base : constant Address := APB1_Peripheral_Base + 16#3400#;
SPI2_Base : constant Address := APB1_Peripheral_Base + 16#3800#;
SPI3_Base : constant Address := APB1_Peripheral_Base + 16#3C00#;
I2S3ext_Base : constant Address := APB1_Peripheral_Base + 16#4000#;
USART2_Base : constant Address := APB1_Peripheral_Base + 16#4400#;
USART3_Base : constant Address := APB1_Peripheral_Base + 16#4800#;
UART4_Base : constant Address := APB1_Peripheral_Base + 16#4C00#;
UART5_Base : constant Address := APB1_Peripheral_Base + 16#5000#;
I2C1_Base : constant Address := APB1_Peripheral_Base + 16#5400#;
I2C2_Base : constant Address := APB1_Peripheral_Base + 16#5800#;
I2C3_Base : constant Address := APB1_Peripheral_Base + 16#5C00#;
CAN1_Base : constant Address := APB1_Peripheral_Base + 16#6400#;
CAN2_Base : constant Address := APB1_Peripheral_Base + 16#6800#;
PWR_Base : constant Address := APB1_Peripheral_Base + 16#7000#;
DAC_Base : constant Address := APB1_Peripheral_Base + 16#7400#;
UART7_BASE : constant Address := APB1_Peripheral_Base + 16#7800#;
UART8_BASE : constant Address := APB1_Peripheral_Base + 16#7C00#;
TIM1_Base : constant Address := APB2_Peripheral_Base + 16#0000#;
TIM8_Base : constant Address := APB2_Peripheral_Base + 16#0400#;
USART1_Base : constant Address := APB2_Peripheral_Base + 16#1000#;
USART6_Base : constant Address := APB2_Peripheral_Base + 16#1400#;
ADC1_Base : constant Address := APB2_Peripheral_Base + 16#2000#;
ADC2_Base : constant Address := APB2_Peripheral_Base + 16#2100#;
ADC3_Base : constant Address := APB2_Peripheral_Base + 16#2200#;
ADC_Base : constant Address := APB2_Peripheral_Base + 16#2300#;
SDIO_Base : constant Address := APB2_Peripheral_Base + 16#2C00#;
SPI1_Base : constant Address := APB2_Peripheral_Base + 16#3000#;
SPI4_BASE : constant Address := APB2_Peripheral_Base + 16#3400#;
SYSCFG_Base : constant Address := APB2_Peripheral_Base + 16#3800#;
EXTI_Base : constant Address := APB2_Peripheral_Base + 16#3C00#;
TIM9_Base : constant Address := APB2_Peripheral_Base + 16#4000#;
TIM10_Base : constant Address := APB2_Peripheral_Base + 16#4400#;
TIM11_Base : constant Address := APB2_Peripheral_Base + 16#4800#;
SPI5_BASE : constant Address := APB2_Peripheral_Base + 16#5000#;
SPI6_BASE : constant Address := APB2_Peripheral_Base + 16#5400#;
SAI1_BASE : constant Address := APB2_Peripheral_Base + 16#5800#;
LTDC_BASE : constant Address := APB2_Peripheral_Base + 16#6800#;
end STM32F4;
|
Revert "Removed aspect "Pack", because it conflicts with aspect "Size""
|
Revert "Removed aspect "Pack", because it conflicts with aspect "Size""
Removing aspect Pack produces an compile error.
This reverts commit 48aec31d3ed3c685ecf9e4d584d10ecec775d6bb.
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
720cd627130c0d28e10ccd8c5d06dab536983f4c
|
src/util-commands-consoles.ads
|
src/util-commands-consoles.ads
|
-----------------------------------------------------------------------
-- util-commands-consoles - Console interface
-- Copyright (C) 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
generic
type Field_Type is (<>);
type Notice_Type is (<>);
package Util.Commands.Consoles is
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
-- Get the field count that was setup through the Print_Title calls.
function Get_Field_Count (Console : in Console_Type) return Natural;
-- Reset the field count.
procedure Clear_Fields (Console : in out Console_Type);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end Util.Commands.Consoles;
|
-----------------------------------------------------------------------
-- util-commands-consoles -- Console interface
-- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
generic
type Field_Type is (<>);
type Notice_Type is (<>);
package Util.Commands.Consoles is
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
-- Get the field count that was setup through the Print_Title calls.
function Get_Field_Count (Console : in Console_Type) return Natural;
-- Reset the field count.
procedure Clear_Fields (Console : in out Console_Type);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end Util.Commands.Consoles;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
88c2ab305785ba8d1949852ef64852257bd5ffe3
|
testcases/spatial1/spatial1.adb
|
testcases/spatial1/spatial1.adb
|
with Ada.Text_IO;
with Spatial_Data; Use Spatial_Data;
procedure Spatial1 is
package TIO renames Ada.Text_IO;
procedure print (shape : Geometry; label : String);
procedure print (shape : Geometry; label : String) is
begin
TIO.Put_Line ("===== " & label & " =====");
TIO.Put_Line ("MySQL: " & mysql_text (shape));
TIO.Put_Line (" WKT: " & Well_Known_Text (shape)); -- (shape));
TIO.Put_Line ("");
end print;
magic_point : constant Geometric_Point := (18.2, -3.4);
magic_linestr : constant Geometric_Line_String := ((0.5, 2.0), (11.0, 4.4), (12.0, 8.1));
magic_polygon : constant Geometric_Polygon := ((0.5, 2.0), (11.0, 4.4), (12.0, 8.1), (0.005, 2.0));
my_point : Geometry := initialize_as_point (magic_point);
my_line : Geometry := initialize_as_line (((4.0, 2.23), (0.25, 5.1)));
my_linestr : Geometry := initialize_as_line_string (magic_linestr);
my_polygon : Geometry := initialize_as_polygon (magic_polygon);
my_circle : Geometry := initialize_as_circle (((2.0, 1.0), 4.5));
my_infline : Geometry := initialize_as_infinite_line (((0.0, 0.0), (2.0, 2.0)));
begin
-- critical checklist
-- =========================================================
-- single point 61
-- single line (converts to line string) 62
-- single infinite line (!) 66
-- single line_string 63
-- single polygon 64
-- single polygon with 1 hole 91-94
-- single polygon with 2 holes 95-98
-- single circle (!) 67
-- point + point = multipoint 76-78
-- point + line_string = collection 106-108
-- point + polygon = collection 110-112
-- point + polygon with 1 hole = 2 item collection 114-115
-- point + polygon hole = EXCEPTION 117-126
-- line_string + line_string = multiline 80-81
-- line_string + point + point = collection 128-130
-- line_string + polygon = collection 132-135
-- line_string + polygon + hole = 2 item collection 136-137
-- polygon + point = 2 item collection 139-142
-- polygon + line_string = 2 item collection 143-146
-- polygon + hole + point + point = 3 item collection 147-151
-- polygon + hole + polygon = 2 item multipolygon 153-156
-- polygon + hole + polygon + point = 3 item collection 158-159
-- polygon + polygon + hole = 2 item multipolygon 161-165
-- polygon + polygon + hole + line_string = 3 item col. 166-167
-- polygon + hole + polygon + hole = 2 item multipolygon 169-174
-- polygon + hole + point = 2 item collection 175-179
-- polygon + hole + line_string = 2 item collection
print (my_point, "SINGLE POINT");
print (my_line, "SINGLE LINE");
print (my_linestr, "SINGLE LINE STRING (THREE POINT)");
print (my_polygon, "SINGLE POLYGON (3 SIDES)");
print (my_circle, "SINGLE CIRCLE (not legal for MySQL or WKT)");
print (my_infline, "INFINITE LINE (converted to regular line on MySQL or WKT)");
declare
pt1 : Geometric_Point := (9.2, 4.773);
pt2 : Geometric_Point := (-7.01, -4.9234);
pt3 : Geometric_Point := (4.5, 6.0);
altpoly : Geometric_Polygon := ((1.0, 2.0), (3.2, 4.5), (8.8, 7.7), (1.0, 2.0));
polyhole1 : Geometry;
polyhole2 : Geometry;
begin
append_point (my_point, pt1);
append_point (my_point, pt2);
print (my_point, "MULTIPOINT COLLECTION");
append_line_string (my_linestr, ((pt3, pt1, pt2)));
print (my_linestr, "MULTILINESTRING COLLECTION");
append_point (my_linestr, pt1);
append_point (my_linestr, pt2);
print (my_linestr, "MIXED COLLECTION #1");
append_point (my_line, pt1);
append_point (my_line, pt2);
print (my_line, "MIXED COLLECTION #2");
append_polygon_hole (my_polygon, (altpoly));
polyhole1 := my_polygon;
print (polyhole1, "STILL SINGLE POLYGON #1");
polyhole2 := polyhole1;
append_polygon_hole (polyhole2, ((13.5, 15.35), (98.1, 11.7), (-13.75, 0.0004), (13.5, 15.35)));
print (polyhole2, "STILL SINGLE POLYGON #2");
append_polygon (my_polygon, ((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
print (my_polygon, "POLYGON COLLECTION #1");
append_point (my_polygon, pt1);
append_point (my_polygon, pt2);
print (my_polygon, "MIXED COLLECTION #3");
my_point := initialize_as_point (magic_point);
append_line_string (my_point, magic_linestr);
print (my_point, "MIXED COLLECTION #4");
my_point := initialize_as_point (magic_point);
append_polygon (my_point, magic_polygon);
print (my_point, "MIXED COLLECTION #5");
append_polygon_hole (my_point, altpoly);
print (my_point, "MIXED COLLECTION #5 ENHANCED");
my_point := initialize_as_point (magic_point);
begin
append_polygon_hole (my_point, altpoly);
print (my_point, "MIXED COLLECTION #5 NEVER SEE THIS");
exception
when others =>
TIO.Put_Line ("You can't add a polygon hole before adding " &
"a polygon");
TIO.Put_Line ("");
end;
my_linestr := initialize_as_line_string (magic_linestr);
append_point (my_linestr, pt1);
print (my_linestr, "MIXED COLLECTION #6");
my_linestr := initialize_as_line_string (magic_linestr);
append_polygon (my_linestr, magic_polygon);
print (my_linestr, "MIXED COLLECTION #7");
append_polygon_hole (my_linestr, altpoly);
print (my_linestr, "MIXED COLLECTION #7 ENHANCED");
my_polygon := initialize_as_polygon (magic_polygon);
append_point (my_polygon, pt2);
print (my_polygon, "MIXED COLLECTION #8");
my_polygon := initialize_as_polygon (magic_polygon);
append_line_string (my_polygon, magic_linestr);
print (my_polygon, "MIXED COLLECTION #9");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon_hole (my_polygon, altpoly);
append_point (my_polygon, pt1);
append_point (my_polygon, pt2);
print (my_polygon, "MIXED COLLECTION #10");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon_hole (my_polygon, altpoly);
append_polygon (my_polygon, ((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
print (my_polygon, "POLYGON COLLECTION #2");
append_point (my_polygon, pt2);
print (my_polygon, "MIXED COLLECTION #11");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon (my_polygon, ((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
append_polygon_hole (my_polygon, altpoly);
print (my_polygon, "POLYGON COLLECTION #3");
append_line_string (my_polygon, magic_linestr);
print (my_polygon, "MIXED COLLECTION #12");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon_hole (my_polygon, altpoly);
append_polygon (my_polygon, ((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
append_polygon_hole (my_polygon, ((13.5, 15.35), (98.1, 11.7), (-13.75, 0.0004), (13.5, 15.35)));
print (my_polygon, "POLYGON COLLECTION #4");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon_hole (my_polygon, altpoly);
append_point (my_polygon, pt3);
print (my_polygon, "MIXED COLLECTION #13");
my_polygon := initialize_as_polygon (magic_polygon);
append_polygon_hole (my_polygon, altpoly);
append_line_string (my_polygon, magic_linestr);
print (my_polygon, "MIXED COLLECTION #14");
end;
end Spatial1;
|
with Ada.Text_IO;
with Spatial_Data; Use Spatial_Data;
procedure Spatial1 is
package TIO renames Ada.Text_IO;
procedure print (shape : Geometry; label : String);
procedure print (shape : Geometry; label : String) is
begin
TIO.Put_Line ("===== " & label & " =====");
TIO.Put_Line ("MySQL: " & mysql_text (shape));
TIO.Put_Line (" WKT: " & Well_Known_Text (shape)); -- (shape));
TIO.Put_Line ("");
end print;
magic_point : constant Geometric_Point := (18.2, -3.4);
magic_linestr : constant Geometric_Line_String := ((0.5, 2.0), (11.0, 4.4), (12.0, 8.1));
magic_polygon : constant Geometric_Polygon := start_polygon (((0.5, 2.0), (11.0, 4.4), (12.0, 8.1), (0.005, 2.0)));
my_point : Geometry := initialize_as_point (magic_point);
my_linestr : Geometry := initialize_as_line (magic_linestr);
my_polygon : Geometry := initialize_as_polygon (magic_polygon);
pt1 : Geometric_Point := (9.2, 4.773);
pt2 : Geometric_Point := (-7.01, -4.9234);
pt3 : Geometric_Point := (4.5, 6.0);
altpoly : Geometric_Ring := ((1.0, 2.0), (3.2, 4.5), (8.8, 7.7), (1.0, 2.0));
polyhole : Geometric_Polygon;
begin
-- critical checklist
-- =========================================================
-- single point 59
-- single line_string 60
-- single polygon 61
-- single polygon with 1 hole 71-74
-- single polygon with 2 holes 66-70
-- point + point = multipoint 72-77
-- point + line_string = collection 94-100
-- point + point(s) = collection 102-108
-- point + polygon = collection 110-115
-- point + polygon with 2 holex = 2 item collection 117-122
-- line_string + line_string = multiline 87-92
-- line_string + point + point = collection 124-130
-- line_string + polygon = collection 132-137
-- line_string + polygon w/holes = 2 item collection 139-144
-- polygon + point = 2 item collection 146-151
-- polygon + line_string = 2 item collection 153-158
-- polygon + hole + point + point = 3 item collection 160-167
-- polygon + hole + polygon + point = 3 item collection 169-176
-- polygon + polygon + hole = 2 item multipolygon 178-182
-- polygon + polygon + hole + line_string = 3 item col. 178-185
-- polygon + hole + polygon + hole = 2 item multipolygon 187-196
-- polygon + hole + point = 2 item collection 198-204
-- polygon + hole + line_string = 2 item collection 206-212
print (my_point, "SINGLE POINT");
print (my_linestr, "SINGLE LINE STRING (THREE POINT)");
print (my_polygon, "SINGLE POLYGON (3 SIDES)");
polyhole := magic_polygon;
append_inner_ring (polyhole, altpoly);
declare
shape : Geometry := initialize_as_polygon (polyhole);
begin
print (shape, "STILL SINGLE POLYGON #1");
end;
append_inner_ring (polyhole, ((13.5, 15.35), (98.1, 11.7), (-13.75, 0.0004), (13.5, 15.35)));
declare
shape : Geometry := initialize_as_polygon (polyhole);
begin
print (shape, "STILL SINGLE POLYGON #2");
end;
declare
MP : Geometry := initialize_as_multi_point (magic_point);
begin
augment_multi_point (MP, pt1);
augment_multi_point (MP, pt2);
print (MP, "MULTIPOINT COLLECTION");
end;
declare
MLS : Geometry := initialize_as_multi_line (magic_linestr);
begin
augment_multi_line (MLS, ((pt3, pt1, pt2)));
print (MLS, "MULTILINESTRING COLLECTION");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_point (pt1));
begin
augment_collection (shape, my_linestr);
print (shape, "MIXED COLLECTION #1 (PT + LINE)");
end;
declare
shape : Geometry := initialize_as_collection (my_point);
begin
augment_collection (shape, initialize_as_point (pt1));
augment_collection (shape, initialize_as_point (pt2));
print (shape, "MIXED COLLECTION #2 (ALL POINTS)");
end;
declare
shape : Geometry := initialize_as_collection (my_point);
begin
augment_collection (shape, my_polygon);
print (shape, "MIXED COLLECTION #3 (PT + POLY)");
end;
declare
shape : Geometry := initialize_as_collection (my_point);
begin
augment_collection (shape, initialize_as_polygon (polyhole));
print (shape, "MIXED COLLECTION #4 (PT + CMPLX POLY)");
end;
declare
shape : Geometry := initialize_as_collection (my_linestr);
begin
augment_collection (shape, initialize_as_point (pt1));
augment_collection (shape, initialize_as_point (pt2));
print (shape, "MIXED COLLECTION #5 (LINE + 2 PT)");
end;
declare
shape : Geometry := initialize_as_collection (my_linestr);
begin
augment_collection (shape, my_polygon);
print (shape, "MIXED COLLECTION #6 (LINE + POLY)");
end;
declare
shape : Geometry := initialize_as_collection (my_linestr);
begin
augment_collection (shape, initialize_as_polygon (polyhole));
print (shape, "MIXED COLLECTION #6 ENHANCED (LINE + CMPLX POLY)");
end;
declare
shape : Geometry := initialize_as_collection (my_polygon);
begin
augment_collection (shape, initialize_as_point (pt2));
print (shape, "MIXED COLLECTION #7 (POLY + PT)");
end;
declare
shape : Geometry := initialize_as_collection (my_polygon);
begin
augment_collection (shape, my_linestr);
print (shape, "MIXED COLLECTION #7 (POLY + LINE)");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_polygon (polyhole));
begin
augment_collection (shape, initialize_as_point (pt1));
augment_collection (shape, initialize_as_point (pt2));
print (shape, "MIXED COLLECTION #8 (CMPLX POLY + 2 PT)");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_polygon (polyhole));
begin
augment_collection (shape, my_polygon);
augment_collection (shape, initialize_as_point (pt2));
print (shape, "MIXED COLLECTION #9 (CMPLX POLY + POLY + PT)");
end;
declare
shape : Geometry := initialize_as_collection (my_polygon);
begin
augment_collection (shape, initialize_as_polygon (polyhole));
print (shape, "MIXED COLLECTION #10 (POLY + CMPLX POLY)");
augment_collection (shape, my_linestr);
print (shape, "MIXED COLLECTION #11 (POLY + CMPLX POLY + LINE)");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_polygon (polyhole));
new_poly : Geometric_Polygon;
begin
new_poly := start_polygon (((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
append_inner_ring (new_poly, ((5.0, 6.0), (1.4, 2.2), (18.1, 24.0), (5.0, 6.0)));
augment_collection (shape, initialize_as_polygon (new_poly));
print (shape, "MIXED COLLECTION #12 (2 CMPLX POLY)");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_polygon (polyhole));
begin
augment_collection (shape, initialize_as_point (pt3));
print (shape, "MIXED COLLECTION #13 (CMPLX POLY + PT)");
end;
declare
shape : Geometry :=
initialize_as_collection (initialize_as_polygon (polyhole));
begin
augment_collection (shape, my_linestr);
print (shape, "MIXED COLLECTION #13 (CMPLX POLY + Line)");
end;
-----------------------------------
-- Additional collection tests --
-----------------------------------
-- Have a collection inside a collection
declare
shape : Geometry := initialize_as_collection (my_point);
shape2 : geometry :=
initialize_as_collection (initialize_as_point (pt3));
begin
augment_collection (shape2, my_linestr);
augment_collection (shape, shape2);
-- print (shape, "COLLECTION THAT CONTAINS ANOTHER COLLECTION");
end;
end Spatial1;
|
Update spatial1 testcase
|
Update spatial1 testcase
Save major progress which proves just about everything works. The
newest test shows that collection inside collection might have an issue
though.
|
Ada
|
isc
|
jrmarino/AdaBase
|
91c3c666f38bdad6fa25b76cd1006d5790384a3f
|
src/asf-parts.ads
|
src/asf-parts.ads
|
-----------------------------------------------------------------------
-- asf-parts -- ASF Parts
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Servlet.Parts;
-- The <b>ASF.Parts</b> package is an Ada implementation of the Java servlet part
-- (JSR 315 3. The Request) provided by the <tt>javax.servlet.http.Part</tt> class.
package ASF.Parts is
-- ------------------------------
-- Multi part content
-- ------------------------------
-- The <b>Part</b> type describes a mime part received in a request.
-- The content is stored in a file and several operations are provided
-- to manage the content.
subtype Part is Servlet.Parts.Part;
-- Get the size of the mime part.
function Get_Size (Data : in Part) return Natural is abstract;
-- Get the content name submitted in the mime part.
function Get_Name (Data : in Part) return String is abstract;
-- Get the path of the local file which contains the part.
function Get_Local_Filename (Data : in Part) return String is abstract;
-- Get the content type of the part.
function Get_Content_Type (Data : in Part) return String is abstract;
-- Write the part data item to the file. This method is not guaranteed to succeed
-- if called more than once for the same part. This allows a particular implementation
-- to use, for example, file renaming, where possible, rather than copying all of
-- the underlying data, thus gaining a significant performance benefit.
procedure Save (Data : in Part;
Path : in String);
-- Deletes the underlying storage for a file item, including deleting any associated
-- temporary disk file.
procedure Delete (Data : in out Part);
end ASF.Parts;
|
-----------------------------------------------------------------------
-- asf-parts -- ASF Parts
-- Copyright (C) 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 Servlet.Parts;
-- The <b>ASF.Parts</b> package is an Ada implementation of the Java servlet part
-- (JSR 315 3. The Request) provided by the <tt>javax.servlet.http.Part</tt> class.
package ASF.Parts is
-- ------------------------------
-- Multi part content
-- ------------------------------
-- The <b>Part</b> type describes a mime part received in a request.
-- The content is stored in a file and several operations are provided
-- to manage the content.
subtype Part is Servlet.Parts.Part;
end ASF.Parts;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c8fd2a1ffb996023a6f93efb18cdc1078b4f4db3
|
mat/src/gtk/mat-targets-gtkmat.ads
|
mat/src/gtk/mat-targets-gtkmat.ads
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
-- with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
private
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
end record;
end MAT.Targets.Gtkmat;
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
-- with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
-- Refresh the information about the current process.
procedure Refresh_Process (Target : in out Target_Type);
private
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
Previous_Event_Counter : Integer := 0;
end record;
end MAT.Targets.Gtkmat;
|
Declare the Refresh_Process procedure and keep track of the last event counter
|
Declare the Refresh_Process procedure and keep track of the last event counter
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
d159c9ee1d45a850888194d78b112cda9e26186f
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with AWA.Storages.Models;
-- == Store Service ==
-- The `AWA.Storages.Stores` package defines the interface that a store must implement to
-- be able to save and retrieve a data content.
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with AWA.Storages.Models;
-- == Store Service ==
-- The `AWA.Storages.Stores` package defines the interface that a store must implement to
-- be able to save and retrieve a data content.
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
Add the database session as parameter to the store implementation
|
Add the database session as parameter to the store implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
32f15bcb83a02a7e21c58da8ac73ea39d4185b4f
|
posix-file.adb
|
posix-file.adb
|
with System;
package body POSIX.File is
function C_Open_Boundary
(File_Name : in String;
Flags : in Flags_t;
Mode : in Permissions.Mode_t) return Descriptor_t is
--# hide C_Open_Boundary
function C_Open
(File_Name : in System.Address;
Flags : in Flags_t;
Mode : in Permissions.Mode_t) return Descriptor_t;
pragma Import (C, C_Open, "open");
begin
return C_Open
(File_Name => File_Name (File_Name'First)'Address,
Flags => Flags,
Mode => Mode);
end C_Open_Boundary;
procedure Open
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Flags : in Flags_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t)
is
C_Flags : Flags_t;
C_File_Name : File_Name_t := File_Name_t'(File_Name_Index_t => Character'Val (0));
begin
-- Reject long filename.
if File_Name'Last >= File_Name_t'Last then
Descriptor := -1;
Error_Value := Error.Error_Name_Too_Long;
else
-- Set flags for non-blocking.
if Non_Blocking then
C_Flags := Flags or O_NONBLOCK;
else
C_Flags := Flags;
end if;
-- Copy and null-terminate filename.
for Index in Positive range File_Name'First .. File_Name'Last loop
C_File_Name (Index) := File_Name (Index);
end loop;
C_File_Name (File_Name'Last + 1) := Character'Val (0);
-- Call system open() procedure.
Descriptor := C_Open_Boundary
(File_Name => C_File_Name,
Flags => C_Flags,
Mode => Mode);
if Descriptor = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end if;
end Open;
procedure Open_Read_Only
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Read_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Read_Only;
procedure Open_Write_Only
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Write_Only;
procedure Open_Exclusive
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Create or Exclusive or Write_Only,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Exclusive;
procedure Open_Append
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Append or Create or Write_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Append;
procedure Open_Truncate
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only or Truncate or Create,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Truncate;
procedure Open_Read_Write
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Read_Write,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Read_Write;
procedure Open_Create
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only or Create,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Create;
end POSIX.File;
|
with System;
package body POSIX.File is
function C_open_Boundary
(File_Name : in String;
Flags : in Flags_t;
Mode : in Permissions.Mode_t) return Descriptor_t is
--# hide C_open_Boundary
function C_open
(File_Name : in System.Address;
Flags : in Flags_t;
Mode : in Permissions.Mode_t) return Descriptor_t;
pragma Import (C, C_open, "open");
begin
return C_open
(File_Name => File_Name (File_Name'First)'Address,
Flags => Flags,
Mode => Mode);
end C_open_Boundary;
procedure Open
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Flags : in Flags_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t)
is
C_Flags : Flags_t;
C_File_Name : File_Name_t := File_Name_t'(File_Name_Index_t => Character'Val (0));
begin
-- Reject long filename.
if File_Name'Last >= File_Name_t'Last then
Descriptor := -1;
Error_Value := Error.Error_Name_Too_Long;
else
-- Set flags for non-blocking.
if Non_Blocking then
C_Flags := Flags or O_NONBLOCK;
else
C_Flags := Flags;
end if;
-- Copy and null-terminate filename.
for Index in Positive range File_Name'First .. File_Name'Last loop
C_File_Name (Index) := File_Name (Index);
end loop;
C_File_Name (File_Name'Last + 1) := Character'Val (0);
-- Call system open() procedure.
Descriptor := C_open_Boundary
(File_Name => C_File_Name,
Flags => C_Flags,
Mode => Mode);
if Descriptor = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end if;
end Open;
procedure Open_Read_Only
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Read_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Read_Only;
procedure Open_Write_Only
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Write_Only;
procedure Open_Exclusive
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Create or Exclusive or Write_Only,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Exclusive;
procedure Open_Append
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Append or Create or Write_Only,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Append;
procedure Open_Truncate
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only or Truncate or Create,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Truncate;
procedure Open_Read_Write
(File_Name : in String;
Non_Blocking : in Boolean;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Read_Write,
Mode => Permissions.None,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Read_Write;
procedure Open_Create
(File_Name : in String;
Non_Blocking : in Boolean;
Mode : in Permissions.Mode_t;
Descriptor : out Descriptor_t;
Error_Value : out Error.Error_t) is
begin
Open
(File_Name => File_Name,
Non_Blocking => Non_Blocking,
Flags => Write_Only or Create,
Mode => Mode,
Descriptor => Descriptor,
Error_Value => Error_Value);
end Open_Create;
procedure Change_Descriptor_Mode
(Descriptor : in Descriptor_t;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t)
is
Return_Value : Error.Return_Value_t;
function C_fchmod
(Descriptor : in Descriptor_t;
Mode : in Permissions.Mode_t) return Error.Return_Value_t;
pragma Import (C, C_fchmod, "fchmod");
begin
Return_Value := C_fchmod
(Descriptor => Descriptor,
Mode => Mode);
case Return_Value is
when -1 => Error_Value := Error.Get_Error;
when 0 => Error_Value := Error.Error_None;
end case;
end Change_Descriptor_Mode;
procedure Change_Mode
(File_Name : in String;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t)
is
Descriptor : Descriptor_t;
begin
Open_Read_Only
(File_Name => File_Name,
Non_Blocking => False,
Descriptor => Descriptor,
Error_Value => Error_Value);
if Error_Value /= Error.Error_None then
Change_Descriptor_Mode
(Descriptor => Descriptor,
Mode => Mode,
Error_Value => Error_Value);
end if;
end Change_Mode;
end POSIX.File;
|
Add Change_Mode and Change_Descriptor_Mode bodies.
|
Add Change_Mode and Change_Descriptor_Mode bodies.
|
Ada
|
isc
|
io7m/coreland-posix-ada,io7m/coreland-posix-ada,io7m/coreland-posix-ada
|
96c3c4a180a286cf50ef78d5e8797485837d5a75
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Wiki_Syntax);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- 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 Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Wiki_Renderer;
Text : in Strings.WString;
Format : in Strings.WString);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer;
Doc : in Documents.Document);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
use Ada.Strings.Wide_Wide_Unbounded;
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Quote_Start, Quote_End, Quote_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Wiki_Syntax := SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Link_First : Boolean := False;
Html_Blockquote : Boolean := False;
Line_Count : Natural := 0;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016, 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.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Wiki_Syntax);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- 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 Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Wiki_Renderer;
Text : in Strings.WString;
Format : in Strings.WString);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer;
Doc : in Documents.Document);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
use Ada.Strings.Wide_Wide_Unbounded;
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Quote_Start, Quote_End, Quote_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer;
Optional : in Boolean := False);
procedure Need_Separator_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Wiki_Syntax := SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Link_First : Boolean := False;
Html_Blockquote : Boolean := False;
Need_Newline : Boolean := False;
Line_Count : Natural := 0;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
Declare the Need_Separator_Line procedure
|
Declare the Need_Separator_Line procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
03eca6eab003f1b7a85b4ac8f8deb99d5e1fc48e
|
awa/src/awa-users-modules.ads
|
awa/src/awa-users-modules.ads
|
-----------------------------------------------------------------------
-- awa-users-module -- User management module
-- 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 ASF.Applications;
with ASF.Security.Servlets;
with AWA.Modules;
with AWA.Users.Services;
with AWA.Users.Filters;
with AWA.Users.Servlets;
-- == Introduction ==
-- The <b>Users.Module</b> manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the <b>Permissions.Module</b>.
--
-- == Configuration ==
-- The *users* module uses a set of configuration properties to configure the OpenID
-- integration.
--
-- @include users.xml
--
-- @include awa-users-services.ads
--
-- @include users.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_user_model.png]
--
-- @include User.hbm.xml
package AWA.Users.Modules is
NAME : constant String := "users";
type User_Module is new AWA.Modules.Module with private;
type User_Module_Access is access all User_Module'Class;
-- Initialize the user module.
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the user manager.
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Get the user module instance associated with the current application.
function Get_User_Module return User_Module_Access;
-- Get the user manager instance associated with the current application.
function Get_User_Manager return Services.User_Service_Access;
private
type User_Module is new AWA.Modules.Module with record
Manager : Services.User_Service_Access := null;
Key_Filter : aliased AWA.Users.Filters.Verify_Filter;
Auth_Filter : aliased AWA.Users.Filters.Auth_Filter;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
end record;
end AWA.Users.Modules;
|
-----------------------------------------------------------------------
-- awa-users-module -- User management module
-- 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 ASF.Applications;
with ASF.Security.Servlets;
with AWA.Modules;
with AWA.Users.Services;
with AWA.Users.Filters;
with AWA.Users.Servlets;
-- == Introduction ==
-- The <b>Users.Module</b> manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the <b>Permissions.Module</b>.
--
-- == Configuration ==
-- The *users* module uses a set of configuration properties to configure the OpenID
-- integration.
--
-- @include users.xml
--
-- @include awa-users-services.ads
--
-- @include users.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_user_model.png]
--
-- @include User.hbm.xml
package AWA.Users.Modules is
NAME : constant String := "users";
type User_Module is new AWA.Modules.Module with private;
type User_Module_Access is access all User_Module'Class;
-- Initialize the user module.
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the user manager.
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Get the user module instance associated with the current application.
function Get_User_Module return User_Module_Access;
-- Get the user manager instance associated with the current application.
function Get_User_Manager return Services.User_Service_Access;
private
type User_Module is new AWA.Modules.Module with record
Manager : Services.User_Service_Access := null;
Key_Filter : aliased AWA.Users.Filters.Verify_Filter;
Auth_Filter : aliased AWA.Users.Filters.Auth_Filter;
Auth : aliased AWA.Users.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
end record;
end AWA.Users.Modules;
|
Use the authenticate servlet defined in the AWA.Users.Servlets package
|
Use the authenticate servlet defined in the AWA.Users.Servlets package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a45abf4f97e5134d4ca32c6765531c966cfa3fee
|
src/wiki-streams-html-builders.adb
|
src/wiki-streams-html-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- 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.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar) is
Code : constant Unicode_Char := Wiki.Strings.WChar'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Start_Element (Name);
Stream.Write_Wide_Text (Content);
Stream.End_Element (Name);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wiki.Strings.WChar := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wiki.Strings.WChar := Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- 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.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar) is
Code : constant Unicode_Char := Wiki.Strings.WChar'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Start_Element (Name);
Stream.Write_Wide_Text (Content);
Stream.End_Element (Name);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wiki.Strings.WChar := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is
Count : constant Natural := Wiki.Strings.Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wiki.Strings.WChar := Wiki.Strings.Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
Use the Wiki.Strings.UString type and operations
|
Use the Wiki.Strings.UString type and operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2b13a668264eba3d137c57e48c6aae8f9f473168
|
mat/src/mat-targets.ads
|
mat/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers.Streams.Sockets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is recieved.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers.Streams.Sockets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is recieved.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
end MAT.Targets;
|
Move the Interactive procedure in MAT.Targets
|
Move the Interactive procedure in MAT.Targets
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
9919994a7679c723e1ee44190253f07e581a3ac5
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with AWA.Storages.Models;
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with AWA.Storages.Models;
-- == Store Service ==
-- The `AWA.Storages.Stores` package defines the interface that a store must implement to
-- be able to save and retrieve a data content.
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f62527203709bd722a16c19bfa579322cb33ad3d
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.ads
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.ads
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for question service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
package AWA.Questions.Services.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Manager : AWA.Questions.Services.Question_Service_Access;
end record;
-- Test creation of a question.
procedure Test_Create_Question (T : in out Test);
-- Test list of questions.
procedure Test_List_Questions (T : in out Test);
end AWA.Questions.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for question service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
package AWA.Questions.Services.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Manager : AWA.Questions.Services.Question_Service_Access;
end record;
-- Test creation of a question.
procedure Test_Create_Question (T : in out Test);
-- Test list of questions.
procedure Test_List_Questions (T : in out Test);
-- Test anonymous user voting for a question.
procedure Test_Question_Vote_Anonymous (T : in out Test);
-- Test voting for a question.
procedure Test_Question_Vote (T : in out Test);
private
-- Do a vote on a question through the question vote bean.
procedure Do_Vote (T : in out Test);
end AWA.Questions.Services.Tests;
|
Add unit tests for the questionVote bean
|
Add unit tests for the questionVote bean
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
127db1c8090610b5e5b10a44d7880af540e8c087
|
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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 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");
-- ------------------------------
-- 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;
-- ------------------------------
-- 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;
-- ------------------------------
-- 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 =>
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.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.
begin
Job.Execute;
exception
when E : others =>
Log.Error ("Exception when executing job {0}", Job.Job.Get_Name);
Log.Error ("Exception: {0}", 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 => True, 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;
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 => Event.Get_Entity_Identifier);
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;
begin
Log.Info ("Restoring job '{0}'", 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;
Work.Execute (DB);
Free (Work);
else
Log.Error ("There is no factory to execute job '{0}'", Name);
Job.Set_Status (AWA.Jobs.Models.FAILED);
DB.Begin_Transaction;
Job.Save (Session => DB);
DB.Commit;
end if;
end;
end;
end Execute;
function Get_Name (Factory : in Job_Factory'Class) return String is
begin
return Ada.Tags.Expanded_Name (Factory'Tag);
end Get_Name;
procedure Set_Work (Job : in out Job_Type;
Work : in Work_Factory'Class) is
begin
Job.Work := Work.Work;
Job.Job.Set_Name (Work.Get_Name);
end Set_Work;
procedure Execute (Job : in out Job_Type) is
begin
Job.Work (Job);
end Execute;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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 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");
-- ------------------------------
-- 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;
-- ------------------------------
-- 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;
-- ------------------------------
-- 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 =>
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.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.
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;
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 => Event.Get_Entity_Identifier);
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;
begin
Log.Info ("Restoring job '{0}'", 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;
Work.Execute (DB);
Free (Work);
else
Log.Error ("There is no factory to execute job '{0}'", 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;
function Get_Name (Factory : in Job_Factory'Class) return String is
begin
return Ada.Tags.Expanded_Name (Factory'Tag);
end Get_Name;
procedure Set_Work (Job : in out Job_Type;
Work : in Work_Factory'Class) is
begin
Job.Work := Work.Work;
Job.Job.Set_Name (Work.Get_Name);
end Set_Work;
procedure Execute (Job : in out Job_Type) is
begin
Job.Work (Job);
end Execute;
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;
|
Fix setting the finish date after job execution
|
Fix setting the finish date after job execution
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
463e4f025d317edefcfd460b1abf898a6638ea1f
|
awa/regtests/awa-users-services-tests.adb
|
awa/regtests/awa-users-services-tests.adb
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
package Caller is new Util.Test_Caller (Test, "Users.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
AWA.Tests.Helpers.Users.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
AWA.Tests.Helpers.Users.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : AWA.Tests.Helpers.Users.Test_User;
T1 : Ada.Calendar.Time;
begin
begin
Principal.Email.Set_Email ("[email protected]");
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
T1 := Ada.Calendar.Clock;
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
-- Storing a date in the database will loose some precision.
T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1");
T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type AWA.Users.Principals.Principal_Access;
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
AWA.Tests.Helpers.Users.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
Principal => Principal.Principal);
T.Assert (Principal.Principal /= null, "No principal returned");
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
AWA.Tests.Helpers.Users.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Modules.User_Module_Access;
begin
declare
M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Modules.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Modules.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
package Caller is new Util.Test_Caller (Test, "Users.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
AWA.Tests.Helpers.Users.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
AWA.Tests.Helpers.Users.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : AWA.Tests.Helpers.Users.Test_User;
T1 : Ada.Calendar.Time;
begin
begin
Principal.Email.Set_Email ("[email protected]");
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
T1 := Ada.Calendar.Clock;
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
-- Storing a date in the database will loose some precision.
T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1");
T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type AWA.Users.Principals.Principal_Access;
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
AWA.Tests.Helpers.Users.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
Principal => Principal.Principal);
T.Assert (Principal.Principal /= null, "No principal returned");
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
AWA.Tests.Helpers.Users.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Modules.User_Module_Access;
begin
declare
M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Modules.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Modules.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
Fix indentation
|
Fix indentation
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
a1a54385ee79d39a00fccc9f6fc2455d6b06c7d1
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Bfd.Symbols;
with Bfd.Files;
with Util.Refs;
with MAT.Types;
package MAT.Symbols.Targets is
type Target_Symbols is new Util.Refs.Ref_Entity with record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Util.Refs;
with MAT.Types;
package MAT.Symbols.Targets is
-- The <tt>Library_Symbols</tt> holds the symbol table associated with
-- a shared library loaded by the program. The <tt>Text_Addr</tt> indicates
-- the text segment address of the loaded library.
type Library_Symbols is new Util.Refs.Ref_Entity with record
Text_Addr : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Library_Symbols_Access is access all Library_Symbols;
package Library_Symbols_Refs is
new Util.Refs.References (Library_Symbols, Library_Symbols_Access);
subtype Library_Symbols_Ref is Library_Symbols_Refs.Ref;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Library_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Library_Symbols_Ref);
type Target_Symbols is new Util.Refs.Ref_Entity with record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Define the Library_Symbols type to hold the symbol table of a shared library Define the Symbols_Maps package to hold a sorted list of shared library symbols
|
Define the Library_Symbols type to hold the symbol table of a shared library
Define the Symbols_Maps package to hold a sorted list of shared library symbols
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3f0bf9c0e5cfa65b4e292a211a6b5067dea6b0b4
|
regtests/util-streams-texts-tests.ads
|
regtests/util-streams-texts-tests.ads
|
-----------------------------------------------------------------------
-- streams.texts.tests -- Unit tests for text streams
-- Copyright (C) 2012, 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.Texts.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading a text stream.
procedure Test_Read_Line (T : in out Test);
-- Write on a text stream converting an integer and writing it.
procedure Test_Write_Integer (T : in out Test);
end Util.Streams.Texts.Tests;
|
-----------------------------------------------------------------------
-- streams.texts.tests -- Unit tests for text streams
-- Copyright (C) 2012, 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.Texts.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading a text stream.
procedure Test_Read_Line (T : in out Test);
-- Write on a text stream converting an integer and writing it.
procedure Test_Write_Integer (T : in out Test);
-- Write on a text stream converting an integer and writing it.
procedure Test_Write_Long_Integer (T : in out Test);
end Util.Streams.Texts.Tests;
|
Declare the Test_Write_Long_Integer procedure
|
Declare the Test_Write_Long_Integer procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1d4e794aa5bac2a9f507b0eba87559732f289ac5
|
src/core/texts/util-texts-builders.adb
|
src/core/texts/util-texts-builders.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Block := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
-- ------------------------------
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List) is
C : Element_Type;
Old_Pos : Natural;
N : Natural := 0;
Pos : Natural := Message'First;
First : Natural := Pos;
begin
-- Replace {N} with arg1, arg2, arg3 or ?
while Pos <= Message'Last loop
C := Message (Pos);
if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
N := 0;
Pos := Pos + 1;
C := Message (Pos);
-- Handle {} replacement to emit the current argument and advance argument position.
if Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Pos - 2;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
N := N + 1;
else
N := 0;
Old_Pos := Pos - 1;
loop
if Element_Type'Pos (C) >= Character'Pos ('0')
and Element_Type'Pos (C) <= Character'Pos ('9')
then
N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0'));
Pos := Pos + 1;
if Pos > Message'Last then
First := Old_Pos;
exit;
end if;
elsif Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Old_Pos;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
exit;
else
First := Old_Pos;
exit;
end if;
C := Message (Pos);
end loop;
end if;
else
Pos := Pos + 1;
end if;
end loop;
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
end Format;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Block := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
-- ------------------------------
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List) is
C : Element_Type;
Old_Pos : Natural;
N : Natural := 0;
Pos : Natural := Message'First;
First : Natural := Pos;
begin
-- Replace {N} with arg1, arg2, arg3 or ?
while Pos <= Message'Last loop
C := Message (Pos);
if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
N := 0;
Pos := Pos + 1;
C := Message (Pos);
-- Handle {} replacement to emit the current argument and advance argument position.
if Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Pos - 2;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
N := N + 1;
else
N := 0;
Old_Pos := Pos - 1;
loop
if Element_Type'Pos (C) >= Character'Pos ('0')
and Element_Type'Pos (C) <= Character'Pos ('9')
then
N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0'));
Pos := Pos + 1;
if Pos > Message'Last then
First := Old_Pos;
exit;
end if;
elsif Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Old_Pos;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
exit;
else
First := Old_Pos;
exit;
end if;
C := Message (Pos);
end loop;
end if;
else
Pos := Pos + 1;
end if;
end loop;
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
end Format;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
Implement Inline_Iterate generic
|
Implement Inline_Iterate generic
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
289fd5cd86061afd35089c047d054df14e8afea1
|
src/core/texts/util-texts-builders.ads
|
src/core/texts/util-texts-builders.ads
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
generic
with procedure Process (Content : in Input);
procedure Inline_Iterate (Source : in Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
Add an Inline_Iterate generic procedure to access the builder using inline and without buffer copy
|
Add an Inline_Iterate generic procedure to access the builder using inline and without buffer copy
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2c87ea9338a31e21cc0f542e14e4cd6a4970f562
|
awa/plugins/awa-counters/src/awa-counters.ads
|
awa/plugins/awa-counters/src/awa-counters.ads
|
-----------------------------------------------------------------------
-- 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 ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- 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);
-- Increment the global counter identified by <tt>Counter</tt>.
procedure Increment (Counter : in Counter_Index_Type);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
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 ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- 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);
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object key <tt>Key</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Key : in ADO.Objects.Object_Key);
-- Increment the global counter identified by <tt>Counter</tt>.
procedure Increment (Counter : in Counter_Index_Type);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
end AWA.Counters;
|
Declare the Increment procedure with the Object_Key type
|
Declare the Increment procedure with the Object_Key type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6731384a41d434ab9379078d5b007827cf8ac864
|
src/natools-s_expressions-file_readers.adb
|
src/natools-s_expressions-file_readers.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.File_Readers is
package Stream_IO renames Ada.Streams.Stream_IO;
overriding procedure Finalize (Object : in out Autoclose) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
end Finalize;
-------------------------
-- S-Expression Reader --
-------------------------
function Reader (Name : String) return S_Reader is
begin
return Object : S_Reader do
Stream_IO.Open (Object.Holder.File, Stream_IO.In_File, Name);
Object.Next;
end return;
end Reader;
procedure Set_Filename (Object : in out S_Reader; Name : in String) is
begin
if Stream_IO.Is_Open (Object.Holder.File) then
Stream_IO.Close (Object.Holder.File);
end if;
Stream_IO.Open (Object.Holder.File, Stream_IO.In_File, Name);
Object.Rewind;
end Set_Filename;
procedure Rewind (Object : in out S_Reader) is
begin
Stream_IO.Set_Index (Object.Holder.File, 1);
Object.Next;
end Rewind;
overriding procedure Read_More
(Object : in out S_Reader;
Buffer : out Atom_Buffers.Atom_Buffer)
is
Data : Ada.Streams.Stream_Element_Array (0 .. 127);
Last : Ada.Streams.Stream_Element_Offset;
begin
Stream_IO.Read (Object.Holder.File, Data, Last);
if Last in Data'Range then
Buffer.Append (Data (Data'First .. Last));
end if;
end Read_More;
-----------------
-- Atom Reader --
-----------------
function Reader (Name : String) return Atom_Reader is
begin
return Object : Atom_Reader do
Stream_IO.Open (Object.File, Stream_IO.In_File, Name);
end return;
end Reader;
procedure Set_Filename (Object : in out Atom_Reader; Name : in String) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
Stream_IO.Open (Object.File, Stream_IO.In_File, Name);
end Set_Filename;
function Length (Object : Atom_Reader) return Count is
begin
return Count (Stream_IO.Size (Object.File));
end Length;
function Read (Object : Atom_Reader) return Atom is
Result : Atom (1 .. Object.Length);
Last : Count;
begin
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Result, Last);
pragma Assert (Last = Result'Last);
return Result;
end Read;
procedure Read
(Object : in Atom_Reader;
Data : out Atom;
Length : out Count) is
begin
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Data, Length);
Length := Object.Length;
end Read;
procedure Read
(Object : in Atom_Reader;
Buffer : out Atom_Buffers.Atom_Buffer;
Block_Size : in Count := 1024)
is
Block : Atom (1 .. Block_Size);
Last : Count;
begin
Buffer.Soft_Reset;
Stream_IO.Set_Index (Object.File, 1);
loop
Stream_IO.Read (Object.File, Block, Last);
exit when Last not in Block'Range;
Buffer.Append (Block (Block'First .. Last));
end loop;
end Read;
procedure Query
(Object : in Atom_Reader;
Process : not null access procedure (Data : in Atom))
is
Buffer : Atom_Access := null;
Last : Count;
begin
Buffer := new Atom (1 .. Object.Length);
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Buffer.all, Last);
pragma Assert (Last = Buffer'Last);
Process (Buffer.all);
Unchecked_Deallocation (Buffer);
exception
when others =>
Unchecked_Deallocation (Buffer);
raise;
end Query;
procedure Block_Query
(Object : in Atom_Reader;
Block_Size : in Count;
Process : not null access procedure (Block : in Atom))
is
Block : Atom (1 .. Block_Size);
Last : Count;
begin
Stream_IO.Set_Index (Object.File, 1);
loop
Stream_IO.Read (Object.File, Block, Last);
exit when Last not in Block'Range;
Process.all (Block (Block'First .. Last));
end loop;
end Block_Query;
overriding procedure Finalize (Object : in out Atom_Reader) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
end Finalize;
end Natools.S_Expressions.File_Readers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.File_Readers is
package Stream_IO renames Ada.Streams.Stream_IO;
overriding procedure Finalize (Object : in out Autoclose) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
end Finalize;
-------------------------
-- S-Expression Reader --
-------------------------
function Reader (Name : String) return S_Reader is
begin
return Object : S_Reader do
Stream_IO.Open (Object.Holder.File, Stream_IO.In_File, Name);
Object.Next;
end return;
end Reader;
procedure Set_Filename (Object : in out S_Reader; Name : in String) is
begin
if Stream_IO.Is_Open (Object.Holder.File) then
Stream_IO.Close (Object.Holder.File);
end if;
Stream_IO.Open (Object.Holder.File, Stream_IO.In_File, Name);
Object.Rewind;
end Set_Filename;
procedure Rewind (Object : in out S_Reader) is
begin
Stream_IO.Set_Index (Object.Holder.File, 1);
Object.Reset;
Object.Next;
end Rewind;
overriding procedure Read_More
(Object : in out S_Reader;
Buffer : out Atom_Buffers.Atom_Buffer)
is
Data : Ada.Streams.Stream_Element_Array (0 .. 127);
Last : Ada.Streams.Stream_Element_Offset;
begin
Stream_IO.Read (Object.Holder.File, Data, Last);
if Last in Data'Range then
Buffer.Append (Data (Data'First .. Last));
end if;
end Read_More;
-----------------
-- Atom Reader --
-----------------
function Reader (Name : String) return Atom_Reader is
begin
return Object : Atom_Reader do
Stream_IO.Open (Object.File, Stream_IO.In_File, Name);
end return;
end Reader;
procedure Set_Filename (Object : in out Atom_Reader; Name : in String) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
Stream_IO.Open (Object.File, Stream_IO.In_File, Name);
end Set_Filename;
function Length (Object : Atom_Reader) return Count is
begin
return Count (Stream_IO.Size (Object.File));
end Length;
function Read (Object : Atom_Reader) return Atom is
Result : Atom (1 .. Object.Length);
Last : Count;
begin
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Result, Last);
pragma Assert (Last = Result'Last);
return Result;
end Read;
procedure Read
(Object : in Atom_Reader;
Data : out Atom;
Length : out Count) is
begin
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Data, Length);
Length := Object.Length;
end Read;
procedure Read
(Object : in Atom_Reader;
Buffer : out Atom_Buffers.Atom_Buffer;
Block_Size : in Count := 1024)
is
Block : Atom (1 .. Block_Size);
Last : Count;
begin
Buffer.Soft_Reset;
Stream_IO.Set_Index (Object.File, 1);
loop
Stream_IO.Read (Object.File, Block, Last);
exit when Last not in Block'Range;
Buffer.Append (Block (Block'First .. Last));
end loop;
end Read;
procedure Query
(Object : in Atom_Reader;
Process : not null access procedure (Data : in Atom))
is
Buffer : Atom_Access := null;
Last : Count;
begin
Buffer := new Atom (1 .. Object.Length);
Stream_IO.Set_Index (Object.File, 1);
Stream_IO.Read (Object.File, Buffer.all, Last);
pragma Assert (Last = Buffer'Last);
Process (Buffer.all);
Unchecked_Deallocation (Buffer);
exception
when others =>
Unchecked_Deallocation (Buffer);
raise;
end Query;
procedure Block_Query
(Object : in Atom_Reader;
Block_Size : in Count;
Process : not null access procedure (Block : in Atom))
is
Block : Atom (1 .. Block_Size);
Last : Count;
begin
Stream_IO.Set_Index (Object.File, 1);
loop
Stream_IO.Read (Object.File, Block, Last);
exit when Last not in Block'Range;
Process.all (Block (Block'First .. Last));
end loop;
end Block_Query;
overriding procedure Finalize (Object : in out Atom_Reader) is
begin
if Stream_IO.Is_Open (Object.File) then
Stream_IO.Close (Object.File);
end if;
end Finalize;
end Natools.S_Expressions.File_Readers;
|
reset parser state in Rewind
|
s_expressions-file_readers: reset parser state in Rewind
|
Ada
|
isc
|
faelys/natools
|
fd7e114ea7970299b6f0e26759499337a7f2226b
|
regtests/util-serialize-io-json-tests.ads
|
regtests/util-serialize-io-json-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
-- Generate some output stream for the test.
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class);
-- Test the JSON output stream generation.
procedure Test_Output (T : in out Test);
-- Test reading a JSON content into an Object tree.
procedure Test_Read (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
-- Generate some output stream for the test.
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class);
-- Test the JSON output stream generation.
procedure Test_Output (T : in out Test);
-- Test the JSON output stream generation (simple JSON documents).
procedure Test_Simple_Output (T : in out Test);
-- Test reading a JSON content into an Object tree.
procedure Test_Read (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
Declare the Test_Simple_Output procedure
|
Declare the Test_Simple_Output procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
baadfc1584d7d7a39d40d256c23bb1479be4a66c
|
src/gen-artifacts-distribs-merges.adb
|
src/gen-artifacts-distribs-merges.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-merges -- Web file merge
-- 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 Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings;
with Util.Streams.Files;
with Util.Streams.Texts;
with EL.Expressions;
with Gen.Utils;
package body Gen.Artifacts.Distribs.Merges is
use Util.Log;
use Ada.Strings.Fixed;
use Util.Beans.Objects;
use Ada.Strings.Unbounded;
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node);
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges");
-- ------------------------------
-- Extract the <property name='{name}'>{value}</property> to setup the
-- EL context to evaluate the source and target links for the merge.
-- ------------------------------
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
use Util.Beans.Objects.Maps;
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
Value : constant String := Gen.Utils.Get_Data_Content (Node);
Pos : constant Natural := Util.Strings.Index (Name, '.');
begin
if Pos = 0 then
Rule.Variables.Bind (Name, To_Object (Value));
return;
end if;
-- A composed name such as 'jquery.path' must be split so that we store
-- the 'path' value within a 'jquery' Map_Bean object. We handle only
-- one such composition.
declare
Param : constant String := Name (Name'First .. Pos - 1);
Tag : constant Unbounded_String := To_Unbounded_String (Param);
Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag);
Val : Object := Rule.Params.Get_Value (Param);
Child : Map_Bean_Access;
begin
if Is_Null (Val) then
Child := new Map_Bean;
Val := To_Object (Child);
Rule.Params.Set_Value (Param, Val);
else
Child := To_Bean (Val);
end if;
Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value));
if Var.Is_Null then
Rule.Variables.Bind (Param, Val);
end if;
end;
end Process_Property;
procedure Iterate_Properties is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property);
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
Result : constant Merge_Rule_Access := new Merge_Rule;
begin
Iterate_Properties (Result.all, Node, "property", False);
Result.Context.Set_Variable_Mapper (Result.Variables'Access);
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String is
pragma Unreferenced (Rule);
begin
return "merge";
end Get_Install_Name;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT);
procedure Error (Message : in String);
function Get_Target_Path (Link : in String) return String;
function Get_Filename (Line : in String) return String;
function Get_Source (Line : in String;
Tag : in String) return String;
procedure Prepare_Merge (Line : in String);
procedure Include (Source : in String);
procedure Process (Line : in String);
Root_Dir : constant String :=
Util.Files.Compose (Context.Get_Result_Directory,
To_String (Rule.Dir));
Source : constant String := Get_Source_Path (Files, False);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : aliased Util.Streams.Files.File_Stream;
Merge : aliased Util.Streams.Files.File_Stream;
Text : Util.Streams.Texts.Print_Stream;
Mode : Mode_Type := MERGE_NONE;
Line_Num : Natural := 0;
procedure Error (Message : in String) is
Line : constant String := Util.Strings.Image (Line_Num);
begin
Context.Error (Source & ":" & Line & ": " & Message);
end Error;
function Get_Target_Path (Link : in String) return String is
Expr : EL.Expressions.Expression;
File : Util.Beans.Objects.Object;
begin
Expr := EL.Expressions.Create_Expression (Link, Rule.Context);
File := Expr.Get_Value (Rule.Context);
return Util.Files.Compose (Root_Dir, To_String (File));
end Get_Target_Path;
function Get_Filename (Line : in String) return String is
Pos : Natural := Index (Line, "link=");
Last : Natural;
begin
if Pos > 0 then
Mode := MERGE_LINK;
else
Pos := Index (Line, "script=");
if Pos > 0 then
Mode := MERGE_SCRIPT;
end if;
if Pos = 0 then
return "";
end if;
end if;
Pos := Index (Line, "=");
Last := Util.Strings.Index (Line, ' ', Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Filename;
function Get_Source (Line : in String;
Tag : in String) return String is
Pos : Natural := Index (Line, Tag);
Last : Natural;
begin
if Pos = 0 then
return "";
end if;
Pos := Pos + Tag'Length;
if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then
return "";
end if;
Last := Util.Strings.Index (Line, Line (Pos), Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Source;
procedure Prepare_Merge (Line : in String) is
Name : constant String := Get_Filename (Line);
Path : constant String := Get_Target_Path (Name);
begin
if Name'Length = 0 then
Error ("invalid file name");
return;
end if;
case Mode is
when MERGE_LINK =>
Text.Write ("<link media='screen' type='text/css' rel='stylesheet'"
& " href='");
Text.Write (Name);
Text.Write ("'/>" & ASCII.LF);
when MERGE_SCRIPT =>
Text.Write ("<script type='text/javascript' src='");
Text.Write (Name);
Text.Write ("'></script>" & ASCII.LF);
when MERGE_NONE =>
null;
end case;
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" create {0}", Path);
end if;
Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File,
Name => Path);
end Prepare_Merge;
procedure Include (Source : in String) is
Target : constant String := Get_Target_Path (Source);
Input : Util.Streams.Files.File_Stream;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" include {0}", Target);
end if;
Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File);
Util.Streams.Copy (From => Input, Into => Merge);
Input.Close;
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex));
end Include;
procedure Process (Line : in String) is
Pos : Natural;
begin
Line_Num := Line_Num + 1;
case Mode is
when MERGE_NONE =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-START ");
if Pos = 0 then
Text.Write (Line);
Text.Write (ASCII.LF);
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Prepare_Merge (Line (Pos + 10 .. Line'Last));
when MERGE_LINK =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Include (Get_Source (Line, "href="));
when MERGE_SCRIPT =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Include (Get_Source (Line, "src="));
end case;
end Process;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info ("webmerge {0}", Path);
end if;
Ada.Directories.Create_Path (Dir);
Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File);
Text.Initialize (Output'Unchecked_Access, 16 * 1024);
Util.Files.Read_File (Source, Process'Access);
Text.Flush;
Output.Close;
end Install;
end Gen.Artifacts.Distribs.Merges;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-merges -- Web file merge
-- 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 Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with EL.Expressions;
with Gen.Utils;
package body Gen.Artifacts.Distribs.Merges is
use Util.Log;
use Ada.Strings.Fixed;
use Util.Beans.Objects;
use Ada.Strings.Unbounded;
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node);
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges");
-- ------------------------------
-- Extract the <property name='{name}'>{value}</property> to setup the
-- EL context to evaluate the source and target links for the merge.
-- ------------------------------
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
use Util.Beans.Objects.Maps;
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
Value : constant String := Gen.Utils.Get_Data_Content (Node);
Pos : constant Natural := Util.Strings.Index (Name, '.');
begin
if Pos = 0 then
Rule.Variables.Bind (Name, To_Object (Value));
return;
end if;
-- A composed name such as 'jquery.path' must be split so that we store
-- the 'path' value within a 'jquery' Map_Bean object. We handle only
-- one such composition.
declare
Param : constant String := Name (Name'First .. Pos - 1);
Tag : constant Unbounded_String := To_Unbounded_String (Param);
Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag);
Val : Object := Rule.Params.Get_Value (Param);
Child : Map_Bean_Access;
begin
if Is_Null (Val) then
Child := new Map_Bean;
Val := To_Object (Child);
Rule.Params.Set_Value (Param, Val);
else
Child := To_Bean (Val);
end if;
Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value));
if Var.Is_Null then
Rule.Variables.Bind (Param, Val);
end if;
end;
end Process_Property;
procedure Process_Replace (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
From : constant String := Gen.Utils.Get_Data_Content (Node, "from");
To : constant String := Gen.Utils.Get_Data_Content (Node, "to");
begin
Rule.Replace.Include (From, To);
end Process_Replace;
procedure Iterate_Properties is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property);
procedure Iterate_Replace is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Replace);
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
Result : constant Merge_Rule_Access := new Merge_Rule;
begin
Iterate_Properties (Result.all, Node, "property", False);
Iterate_Replace (Result.all, Node, "replace", False);
Result.Context.Set_Variable_Mapper (Result.Variables'Access);
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String is
pragma Unreferenced (Rule);
begin
return "merge";
end Get_Install_Name;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
use Ada.Streams;
type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT);
procedure Error (Message : in String);
function Get_Target_Path (Link : in String) return String;
function Get_Filename (Line : in String) return String;
function Get_Source (Line : in String;
Tag : in String) return String;
procedure Prepare_Merge (Line : in String);
procedure Include (Source : in String);
procedure Process (Line : in String);
Root_Dir : constant String :=
Util.Files.Compose (Context.Get_Result_Directory,
To_String (Rule.Dir));
Source : constant String := Get_Source_Path (Files, False);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : aliased Util.Streams.Files.File_Stream;
Merge : aliased Util.Streams.Files.File_Stream;
Text : Util.Streams.Texts.Print_Stream;
Mode : Mode_Type := MERGE_NONE;
Line_Num : Natural := 0;
procedure Error (Message : in String) is
Line : constant String := Util.Strings.Image (Line_Num);
begin
Context.Error (Source & ":" & Line & ": " & Message);
end Error;
function Get_Target_Path (Link : in String) return String is
Expr : EL.Expressions.Expression;
File : Util.Beans.Objects.Object;
begin
Expr := EL.Expressions.Create_Expression (Link, Rule.Context);
File := Expr.Get_Value (Rule.Context);
return Util.Files.Compose (Root_Dir, To_String (File));
end Get_Target_Path;
function Get_Filename (Line : in String) return String is
Pos : Natural := Index (Line, "link=");
Last : Natural;
begin
if Pos > 0 then
Mode := MERGE_LINK;
else
Pos := Index (Line, "script=");
if Pos > 0 then
Mode := MERGE_SCRIPT;
end if;
if Pos = 0 then
return "";
end if;
end if;
Pos := Index (Line, "=");
Last := Util.Strings.Index (Line, ' ', Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Filename;
function Get_Source (Line : in String;
Tag : in String) return String is
Pos : Natural := Index (Line, Tag);
Last : Natural;
begin
if Pos = 0 then
return "";
end if;
Pos := Pos + Tag'Length;
if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then
return "";
end if;
Last := Util.Strings.Index (Line, Line (Pos), Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Source;
procedure Prepare_Merge (Line : in String) is
Name : constant String := Get_Filename (Line);
Path : constant String := Get_Target_Path (Name);
begin
if Name'Length = 0 then
Error ("invalid file name");
return;
end if;
case Mode is
when MERGE_LINK =>
Text.Write ("<link media='screen' type='text/css' rel='stylesheet'"
& " href='");
Text.Write (Name);
Text.Write ("'/>" & ASCII.LF);
when MERGE_SCRIPT =>
Text.Write ("<script type='text/javascript' src='");
Text.Write (Name);
Text.Write ("'></script>" & ASCII.LF);
when MERGE_NONE =>
null;
end case;
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" create {0}", Path);
end if;
Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File,
Name => Path);
end Prepare_Merge;
Current_Match : Util.Strings.Maps.Cursor;
function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset is
Iter : Util.Strings.Maps.Cursor := Rule.Replace.First;
First : Stream_Element_Offset := Buffer'Last + 1;
begin
while Util.Strings.Maps.Has_Element (Iter) loop
declare
Value : constant String := Util.Strings.Maps.Key (Iter);
Match : Stream_Element_Array (1 .. Value'Length);
for Match'Address use Value'Address;
Pos : Stream_Element_Offset;
begin
Pos := Buffer'First;
while Pos + Match'Length < Buffer'Last loop
if Buffer (Pos .. Pos + Match'Length - 1) = Match then
if First > Pos then
First := Pos;
Current_Match := Iter;
end if;
exit;
end if;
Pos := Pos + 1;
end loop;
end;
Util.Strings.Maps.Next (Iter);
end loop;
return First;
end Find_Match;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Ada.Streams.Stream_Element_Array,
Name => Util.Streams.Buffered.Buffer_Access);
procedure Include (Source : in String) is
Target : constant String := Get_Target_Path (Source);
Input : Util.Streams.Files.File_Stream;
Size : Stream_Element_Offset;
Last : Stream_Element_Offset;
Pos : Stream_Element_Offset;
Next : Stream_Element_Offset;
Buffer : Util.Streams.Buffered.Buffer_Access;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" include {0}", Target);
end if;
Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File);
Size := Stream_Element_Offset (Ada.Directories.Size (Target));
Buffer := new Stream_Element_Array (1 .. Size);
Input.Read (Buffer.all, Last);
Input.Close;
Pos := 1;
while Pos < Last loop
Next := Find_Match (Buffer (Pos .. Last));
if Next > Pos then
Merge.Write (Buffer (Pos .. Next - 1));
end if;
exit when Next >= Last;
declare
Value : constant String := Util.Strings.Maps.Key (Current_Match);
Replace : constant String := Util.Strings.Maps.Element (Current_Match);
Content : Stream_Element_Array (1 .. Replace'Length);
for Content'Address use Replace'Address;
begin
Merge.Write (Content);
Pos := Next + Value'Length;
end;
end loop;
Free (Buffer);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex));
end Include;
procedure Process (Line : in String) is
Pos : Natural;
begin
Line_Num := Line_Num + 1;
case Mode is
when MERGE_NONE =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-START ");
if Pos = 0 then
Text.Write (Line);
Text.Write (ASCII.LF);
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Prepare_Merge (Line (Pos + 10 .. Line'Last));
when MERGE_LINK =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Include (Get_Source (Line, "href="));
when MERGE_SCRIPT =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Include (Get_Source (Line, "src="));
end case;
end Process;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info ("webmerge {0}", Path);
end if;
Ada.Directories.Create_Path (Dir);
Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File);
Text.Initialize (Output'Unchecked_Access, 16 * 1024);
Util.Files.Read_File (Source, Process'Access);
Text.Flush;
Output.Close;
end Install;
end Gen.Artifacts.Distribs.Merges;
|
Add support to replace some texts by another when merging the CSS files
|
Add support to replace some texts by another when merging the CSS files
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3e77293ba1be5a8f67d8d42dabad2a8c84fd437c
|
src/asf-components-ajax-includes.adb
|
src/asf-components-ajax-includes.adb
|
-----------------------------------------------------------------------
-- components-ajax-includes -- AJAX Include 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.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Root;
with ASF.Contexts.Writer;
package body ASF.Components.Ajax.Includes is
-- ------------------------------
-- Get the HTML layout that must be used for the include container.
-- The default layout is a "div".
-- Returns "div", "span", "pre", "b".
-- ------------------------------
function Get_Layout (UI : in UIInclude;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Layout : constant String := UI.Get_Attribute (Name => LAYOUT_ATTR_NAME,
Context => Context,
Default => "div");
begin
if Layout = "div" or Layout = "span" or Layout = "pre" or Layout = "b" then
return Layout;
else
return "div";
end if;
end Get_Layout;
-- ------------------------------
-- The included XHTML file is rendered according to the <b>async</b> attribute:
--
-- When <b>async</b> is false, render the specified XHTML file in such a way that inner
-- forms will be posted on the included view.
--
-- When <b>async</b> is true, trigger an AJAX call to include the specified
-- XHTML view when the page is loaded.
--
--
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIInclude;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application;
View_Handler : constant access ASF.Applications.Views.View_Handler'Class
:= App.Get_View_Handler;
Id : constant Ada.Strings.Unbounded.Unbounded_String := UI.Get_Client_Id;
Layout : constant String := UIInclude'Class (UI).Get_Layout (Context);
Async : constant Boolean := UI.Get_Attribute (Name => ASYNC_ATTR_NAME,
Context => Context,
Default => False);
Page : constant String := UI.Get_Attribute (Name => SRC_ATTR_NAME,
Context => Context,
Default => "");
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element (Layout);
UI.Render_Attributes (Context, Writer);
-- In Async mode, generate the javascript code to trigger the async update of
-- the generated div/span.
if Async then
Writer.Queue_Script ("ASF.Update(""");
Writer.Queue_Script (Id);
Writer.Queue_Script (""", """);
Writer.Queue_Script (View_Handler.Get_Action_URL (Context, Page));
Writer.Queue_Script (""");");
else
-- Include the view content as if the user fetched the patch. This has almost the
-- same final result except that the inner content is returned now and not by
-- another async http GET request.
declare
View : constant ASF.Components.Root.UIViewRoot := Context.Get_View_Root;
Include_View : ASF.Components.Root.UIViewRoot;
Is_Ajax : constant Boolean := Context.Is_Ajax_Request;
Content_Type : constant String := Context.Get_Response.Get_Content_Type;
begin
Context.Set_Ajax_Request (True);
View_Handler.Restore_View (Page, Context, Include_View);
Context.Set_View_Root (Include_View);
View_Handler.Render_View (Context, Include_View);
Context.Get_Response.Set_Content_Type (Content_Type);
Context.Set_View_Root (View);
Context.Set_Ajax_Request (Is_Ajax);
exception
when others =>
Context.Get_Response.Set_Content_Type (Content_Type);
Context.Set_View_Root (View);
Context.Set_Ajax_Request (Is_Ajax);
raise;
end;
end if;
Writer.End_Element (Layout);
end;
end Encode_Children;
end ASF.Components.Ajax.Includes;
|
-----------------------------------------------------------------------
-- components-ajax-includes -- AJAX Include 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.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Root;
with ASF.Contexts.Writer;
package body ASF.Components.Ajax.Includes is
-- ------------------------------
-- Get the HTML layout that must be used for the include container.
-- The default layout is a "div".
-- Returns "div", "span", "pre", "b".
-- ------------------------------
function Get_Layout (UI : in UIInclude;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Layout : constant String := UI.Get_Attribute (Name => LAYOUT_ATTR_NAME,
Context => Context,
Default => "div");
begin
if Layout = "div" or Layout = "span" or Layout = "pre" or Layout = "b" then
return Layout;
else
return "div";
end if;
end Get_Layout;
-- ------------------------------
-- The included XHTML file is rendered according to the <b>async</b> attribute:
--
-- When <b>async</b> is false, render the specified XHTML file in such a way that inner
-- forms will be posted on the included view.
--
-- When <b>async</b> is true, trigger an AJAX call to include the specified
-- XHTML view when the page is loaded.
--
--
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIInclude;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application;
View_Handler : constant access ASF.Applications.Views.View_Handler'Class
:= App.Get_View_Handler;
Id : constant Ada.Strings.Unbounded.Unbounded_String := UI.Get_Client_Id;
Layout : constant String := UIInclude'Class (UI).Get_Layout (Context);
Async : constant Boolean := UI.Get_Attribute (Name => ASYNC_ATTR_NAME,
Context => Context,
Default => False);
Page : constant String := UI.Get_Attribute (Name => SRC_ATTR_NAME,
Context => Context,
Default => "");
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element (Layout);
UI.Render_Attributes (Context, Writer);
-- In Async mode, generate the javascript code to trigger the async update of
-- the generated div/span.
if Async then
Writer.Write_Attribute ("id", Id);
Writer.Queue_Script ("ASF.Update(null,""");
Writer.Queue_Script (View_Handler.Get_Action_URL (Context, Page));
Writer.Queue_Script (""", ""#");
Writer.Queue_Script (Id);
Writer.Queue_Script (""");");
else
-- Include the view content as if the user fetched the patch. This has almost the
-- same final result except that the inner content is returned now and not by
-- another async http GET request.
declare
View : constant ASF.Components.Root.UIViewRoot := Context.Get_View_Root;
Include_View : ASF.Components.Root.UIViewRoot;
Is_Ajax : constant Boolean := Context.Is_Ajax_Request;
Content_Type : constant String := Context.Get_Response.Get_Content_Type;
begin
Context.Set_Ajax_Request (True);
View_Handler.Restore_View (Page, Context, Include_View);
Context.Set_View_Root (Include_View);
View_Handler.Render_View (Context, Include_View);
Context.Get_Response.Set_Content_Type (Content_Type);
Context.Set_View_Root (View);
Context.Set_Ajax_Request (Is_Ajax);
exception
when others =>
Context.Get_Response.Set_Content_Type (Content_Type);
Context.Set_View_Root (View);
Context.Set_Ajax_Request (Is_Ajax);
raise;
end;
end if;
Writer.End_Element (Layout);
end;
end Encode_Children;
end ASF.Components.Ajax.Includes;
|
Fix generation of javascript when rendering an ajax include in async mode
|
Fix generation of javascript when rendering an ajax include in async mode
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
b2ef16c15882878c8de142dc4943821ec59b284f
|
src/util-dates-rfc7231.ads
|
src/util-dates-rfc7231.ads
|
-----------------------------------------------------------------------
-- util-dates-rfc7231-- RFC7231 date format utilities
-- 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.Calendar;
with Util.Strings.Builders;
package Util.Dates.RFC7231 is
-- Parses a HTTP date that follows the RFC7231 or RFC2616 format.
-- Raises Constraint_Error if the date format is not recognized.
function Value (Date : in String) return Ada.Calendar.Time;
-- Return the RFC7231/RFC2616 date format.
function Image (Date : in Ada.Calendar.Time) return String;
-- Append the date in RFC7231/RFC2616 format in the string builder.
-- The date separator can be changed to '-' to generate a cookie expires date.
procedure Append_Date (Into : in out Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Date_Separator : in Character := ' ');
end Util.Dates.RFC7231;
|
-----------------------------------------------------------------------
-- util-dates-rfc7231-- RFC7231 date format utilities
-- Copyright (C) 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.Calendar;
with Util.Strings.Builders;
-- == RFC7231 Dates ==
-- The RFC7231 defines a standard date format that is used by HTTP headers.
-- The `Util.Dates.RFC7231` package provides an `Image` function to convert a date into
-- that target format and a `Value` function to parse such format string and return the date.
--
-- Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
-- S : constant String := Util.Dates.RFC7231.Image (Now);
-- Date : Ada.Calendar.time := Util.Dates.RFC7231.Value (S);
--
-- A `Constraint_Error` exception is raised when the date string is not in the correct format.
package Util.Dates.RFC7231 is
-- Parses a HTTP date that follows the RFC7231 or RFC2616 format.
-- Raises Constraint_Error if the date format is not recognized.
function Value (Date : in String) return Ada.Calendar.Time;
-- Return the RFC7231/RFC2616 date format.
function Image (Date : in Ada.Calendar.Time) return String;
-- Append the date in RFC7231/RFC2616 format in the string builder.
-- The date separator can be changed to '-' to generate a cookie expires date.
procedure Append_Date (Into : in out Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Date_Separator : in Character := ' ');
end Util.Dates.RFC7231;
|
Add and update the documentation
|
Add and update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
279d9b8dc9988f2969cc73dad138bd0797259bac
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage instance stored in a folder and identified by a name.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
Declare new Load_Storage procedure to load a storage file from the folder ID and file name
|
Declare new Load_Storage procedure to load a storage file from the folder ID and file name
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a1d3a6ec79b8de5ff6e58aa7a9604034af78b572
|
components/src/motion/ak8963/ak8963.adb
|
components/src/motion/ak8963/ak8963.adb
|
with Ada.Unchecked_Conversion;
with Ada.Real_Time; use Ada.Real_Time;
with Interfaces; use Interfaces;
with HAL.I2C; use HAL.I2C;
package body AK8963 is
AK9863_ADDRESS_00 : constant := 16#18#;
AK9863_ADDRESS_01 : constant := 16#1A#;
AK9863_ADDRESS_10 : constant := 16#1C#;
AK9863_ADDRESS_11 : constant := 16#1E#;
AK8963_RA_WIA : constant := 16#00#;
-- AK8963_RA_INFO : constant := 16#01#;
AK8963_RA_ST1 : constant := 16#02#;
AK8963_RA_HXL : constant := 16#03#;
-- AK8963_RA_HXH : constant := 16#04#;
-- AK8963_RA_HYL : constant := 16#05#;
-- AK8963_RA_HYH : constant := 16#06#;
-- AK8963_RA_HZL : constant := 16#07#;
-- AK8963_RA_HZH : constant := 16#08#;
AK8963_RA_ST2 : constant := 16#09#;
AK8963_RA_CNTL : constant := 16#0A#;
-- AK8963_RA_RSV : constant := 16#0B#;
AK8963_RA_ASTC : constant := 16#0C#;
-- AK8963_RA_I2CDIS : constant := 16#0F#;
AK8963_RA_ASAX : constant := 16#10#;
-- AK8963_RA_ASAY : constant := 16#11#;
-- AK8963_RA_ASAZ : constant := 16#12#;
-- In 16-bit output, decimal value 32760 is 4912 micro Tesla
-- so 49.12 Gauss
MAG_TO_GAUSS : constant := 49.12 / 32_760.0;
AK8963_ST_X_MIN : constant := -200.0 * MAG_TO_GAUSS;
AK8963_ST_X_MAX : constant := 200 * MAG_TO_GAUSS;
AK8963_ST_Y_MIN : constant := -200 * MAG_TO_GAUSS;
AK8963_ST_Y_MAX : constant := 200 * MAG_TO_GAUSS;
AK8963_ST_Z_MIN : constant := -3200 * MAG_TO_GAUSS;
AK8963_ST_Z_MAX : constant := -800 * MAG_TO_GAUSS;
function I2C_Read
(Device : AK8963_Device;
Reg : Short) return Byte;
function I2C_Read
(Device : AK8963_Device;
Reg : Short;
Bit : Natural) return Boolean;
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Data : Byte);
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Bit : Natural;
State : Boolean);
--------------
-- I2C_Read --
--------------
function I2C_Read
(Device : AK8963_Device;
Reg : Short) return Byte
is
Data : I2C_Data (1 .. 1);
Status : I2C_Status;
begin
Device.I2C_Port.Mem_Read
(Device.Address,
Reg,
Memory_Size_8b,
Data,
Status);
return Data (1);
end I2C_Read;
--------------
-- I2C_Read --
--------------
function I2C_Read
(Device : AK8963_Device;
Reg : Short;
Bit : Natural) return Boolean
is
Mask : constant Byte := 2 ** Bit;
Data : constant Byte := I2C_Read (Device, Reg);
begin
return (Data and Mask) /= 0;
end I2C_Read;
---------------
-- I2C_Write --
---------------
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Data : Byte)
is
Status : I2C_Status with Unreferenced;
begin
Device.I2C_Port.Mem_Write
(Device.Address,
Reg,
Memory_Size_8b,
(1 => Data),
Status);
end I2C_Write;
---------------
-- I2C_Write --
---------------
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Bit : Natural;
State : Boolean)
is
Val : Byte := I2C_Read (Device, Reg);
Mask : constant Byte := 2 ** Bit;
begin
if State then
Val := Val or Mask;
else
Val := Val and not Mask;
end if;
I2C_Write (Device, Reg, Val);
end I2C_Write;
----------------
-- Initialize --
----------------
procedure Initialize (Device : in out AK8963_Device)
is
begin
if Device.Is_Init then
return;
end if;
Device.Address :=
(case Device.Address_Selector is
when Add_00 => AK9863_ADDRESS_00,
when Add_01 => AK9863_ADDRESS_01,
when Add_10 => AK9863_ADDRESS_10,
when Add_11 => AK9863_ADDRESS_11);
Device.Is_Init := True;
end Initialize;
---------------------
-- Test_Connection --
---------------------
function Test_Connection (Device : AK8963_Device) return Boolean
is
Data : HAL.I2C.I2C_Data (1 .. 1) := (others => 0);
Status : HAL.I2C.I2C_Status;
begin
Device.I2C_Port.Mem_Read
(Device.Address,
AK8963_RA_WIA,
HAL.I2C.Memory_Size_8b,
Data,
Status);
return Status = Ok and then Data (1) = 16#48#;
end Test_Connection;
---------------
-- Self_Test --
---------------
function Self_Test (Device : in out AK8963_Device) return Boolean
is
Mx, My, Mz : Gauss;
Conf_Save : Byte;
Retry : Natural := 20;
Ret : Boolean;
Dead : Boolean with Unreferenced;
begin
if not Test_Connection (Device) then
return False;
end if;
Ret := True;
-- Save the current configuration
Conf_Save := I2C_Read (Device, AK8963_RA_CNTL);
-- Power_Down
Set_Mode (Device, Power_Down);
I2C_Write (Device, AK8963_RA_ASTC, 6, True); -- Set SELF bit to True
Dead := Get_Overflow_Status (Device); -- Clears ST1 by reading ST2
Set_Mode (Device, Self_Test, Mode_16bit);
while Retry > 0 loop
exit when Get_Data_Ready (Device);
Retry := Retry - 1;
delay until Clock + Milliseconds (10);
end loop;
if Retry = 0 then
Ret := False;
end if;
Get_Heading (Device, Mx, My, Mz);
Dead := Get_Overflow_Status (Device); -- Clears ST1 by reading ST2
I2C_Write (Device, AK8963_RA_ASTC, 6, False); -- Set SELF bit to False
Set_Mode (Device, Power_Down);
if Mx < AK8963_ST_X_MIN
or else Mx > AK8963_ST_X_MAX
or else My < AK8963_ST_Y_MIN
or else My > AK8963_ST_Y_MAX
or else Mz < AK8963_ST_Z_MIN
or else Mz > AK8963_ST_Z_MAX
then
Ret := False;
end if;
-- Set back the saved config
I2C_Write (Device, AK8963_RA_CNTL, Conf_Save);
return Ret;
end Self_Test;
--------------
-- Set_Mode --
--------------
procedure Set_Mode
(Device : in out AK8963_Device;
Operation_Mode : AK8963_Operation_Mode;
Sampling_Mode : AK8963_Sampling_Mode)
is
Mode : constant Byte :=
AK8963_Operation_Mode'Enum_Rep (Operation_Mode)
or AK8963_Sampling_Mode'Enum_Rep (Sampling_Mode);
begin
I2C_Write (Device, AK8963_RA_CNTL, Mode);
end Set_Mode;
--------------
-- Set_Mode --
--------------
procedure Set_Mode
(Device : in out AK8963_Device;
Operation_Mode : AK8963_Operation_Mode)
is
Mode : constant Byte :=
AK8963_Operation_Mode'Enum_Rep (Operation_Mode);
begin
I2C_Write (Device, AK8963_RA_CNTL, Mode);
end Set_Mode;
--------------------
-- Get_Data_Ready --
--------------------
function Get_Data_Ready (Device : AK8963_Device) return Boolean
is
AK8963_ST1_DRDY_BIT : constant := 0;
begin
return I2C_Read (Device, AK8963_RA_ST1, AK8963_ST1_DRDY_BIT);
end Get_Data_Ready;
-----------------
-- Get_Heading --
-----------------
procedure Get_Heading
(Device : AK8963_Device;
Mx, My, Mz : out Float)
is
Buffer : I2C_Data (1 .. 6);
Status : I2C_Status;
function To_Signed is new
Ada.Unchecked_Conversion (Unsigned_16, Integer_16);
begin
Mem_Read
(Device.I2C_Port.all,
Addr => Device.Address,
Mem_Addr => AK8963_RA_HXL,
Mem_Addr_Size => Memory_Size_8b,
Data => Buffer,
Status => Status);
if Status /= Ok then
Mx := 0.0;
My := 0.0;
Mz := 0.0;
else
Mx :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (2)), 8)
or Unsigned_16 (Buffer (1)))) * MAG_TO_GAUSS;
My :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (4)), 8)
or Unsigned_16 (Buffer (3)))) * MAG_TO_GAUSS;
Mz :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (6)), 8)
or Unsigned_16 (Buffer (5)))) * MAG_TO_GAUSS;
-- Read the sensitivity adjustment data
Mem_Read
(Device.I2C_Port.all,
Addr => Device.Address,
Mem_Addr => AK8963_RA_ASAX,
Mem_Addr_Size => Memory_Size_8b,
Data => Buffer (1 .. 3),
Status => Status);
if Status = Ok then
Mx := Mx * ((Float (Buffer (1)) - 128.0) / 256.0 + 1.0);
My := My * ((Float (Buffer (1)) - 128.0) / 256.0 + 1.0);
Mz := Mz * ((Float (Buffer (1)) - 128.0) / 256.0 + 1.0);
end if;
end if;
end Get_Heading;
-------------------------
-- Get_Overflow_Status --
-------------------------
function Get_Overflow_Status (Device : AK8963_Device) return Boolean
is
AK8963_ST2_HOFL_BIT : constant := 3;
begin
return I2C_Read (Device, AK8963_RA_ST2, AK8963_ST2_HOFL_BIT);
end Get_Overflow_Status;
end AK8963;
|
with Ada.Unchecked_Conversion;
with Ada.Real_Time; use Ada.Real_Time;
with Interfaces; use Interfaces;
with HAL.I2C; use HAL.I2C;
package body AK8963 is
AK9863_ADDRESS_00 : constant := 16#18#;
AK9863_ADDRESS_01 : constant := 16#1A#;
AK9863_ADDRESS_10 : constant := 16#1C#;
AK9863_ADDRESS_11 : constant := 16#1E#;
AK8963_RA_WIA : constant := 16#00#;
-- AK8963_RA_INFO : constant := 16#01#;
AK8963_RA_ST1 : constant := 16#02#;
AK8963_RA_HXL : constant := 16#03#;
-- AK8963_RA_HXH : constant := 16#04#;
-- AK8963_RA_HYL : constant := 16#05#;
-- AK8963_RA_HYH : constant := 16#06#;
-- AK8963_RA_HZL : constant := 16#07#;
-- AK8963_RA_HZH : constant := 16#08#;
AK8963_RA_ST2 : constant := 16#09#;
AK8963_RA_CNTL : constant := 16#0A#;
-- AK8963_RA_RSV : constant := 16#0B#;
AK8963_RA_ASTC : constant := 16#0C#;
-- AK8963_RA_I2CDIS : constant := 16#0F#;
AK8963_RA_ASAX : constant := 16#10#;
-- AK8963_RA_ASAY : constant := 16#11#;
-- AK8963_RA_ASAZ : constant := 16#12#;
-- In 16-bit output, decimal value 32760 is 4912 micro Tesla
-- so 49.12 Gauss
MAG_TO_GAUSS : constant := 49.12 / 32_760.0;
AK8963_ST_X_MIN : constant := -200.0 * MAG_TO_GAUSS;
AK8963_ST_X_MAX : constant := 200 * MAG_TO_GAUSS;
AK8963_ST_Y_MIN : constant := -200 * MAG_TO_GAUSS;
AK8963_ST_Y_MAX : constant := 200 * MAG_TO_GAUSS;
AK8963_ST_Z_MIN : constant := -3200 * MAG_TO_GAUSS;
AK8963_ST_Z_MAX : constant := -800 * MAG_TO_GAUSS;
function I2C_Read
(Device : AK8963_Device;
Reg : Short) return Byte;
function I2C_Read
(Device : AK8963_Device;
Reg : Short;
Bit : Natural) return Boolean;
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Data : Byte);
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Bit : Natural;
State : Boolean);
--------------
-- I2C_Read --
--------------
function I2C_Read
(Device : AK8963_Device;
Reg : Short) return Byte
is
Data : I2C_Data (1 .. 1);
Status : I2C_Status;
begin
Device.I2C_Port.Mem_Read
(Device.Address,
Reg,
Memory_Size_8b,
Data,
Status);
return Data (1);
end I2C_Read;
--------------
-- I2C_Read --
--------------
function I2C_Read
(Device : AK8963_Device;
Reg : Short;
Bit : Natural) return Boolean
is
Mask : constant Byte := 2 ** Bit;
Data : constant Byte := I2C_Read (Device, Reg);
begin
return (Data and Mask) /= 0;
end I2C_Read;
---------------
-- I2C_Write --
---------------
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Data : Byte)
is
Status : I2C_Status with Unreferenced;
begin
Device.I2C_Port.Mem_Write
(Device.Address,
Reg,
Memory_Size_8b,
(1 => Data),
Status);
end I2C_Write;
---------------
-- I2C_Write --
---------------
procedure I2C_Write
(Device : AK8963_Device;
Reg : Short;
Bit : Natural;
State : Boolean)
is
Val : Byte := I2C_Read (Device, Reg);
Mask : constant Byte := 2 ** Bit;
begin
if State then
Val := Val or Mask;
else
Val := Val and not Mask;
end if;
I2C_Write (Device, Reg, Val);
end I2C_Write;
----------------
-- Initialize --
----------------
procedure Initialize (Device : in out AK8963_Device)
is
begin
if Device.Is_Init then
return;
end if;
Device.Address :=
(case Device.Address_Selector is
when Add_00 => AK9863_ADDRESS_00,
when Add_01 => AK9863_ADDRESS_01,
when Add_10 => AK9863_ADDRESS_10,
when Add_11 => AK9863_ADDRESS_11);
Device.Is_Init := True;
end Initialize;
---------------------
-- Test_Connection --
---------------------
function Test_Connection (Device : AK8963_Device) return Boolean
is
Data : HAL.I2C.I2C_Data (1 .. 1) := (others => 0);
Status : HAL.I2C.I2C_Status;
begin
Device.I2C_Port.Mem_Read
(Device.Address,
AK8963_RA_WIA,
HAL.I2C.Memory_Size_8b,
Data,
Status);
return Status = Ok and then Data (1) = 16#48#;
end Test_Connection;
---------------
-- Self_Test --
---------------
function Self_Test (Device : in out AK8963_Device) return Boolean
is
Mx, My, Mz : Gauss;
Conf_Save : Byte;
Retry : Natural := 20;
Ret : Boolean;
Dead : Boolean with Unreferenced;
begin
if not Test_Connection (Device) then
return False;
end if;
Ret := True;
-- Save the current configuration
Conf_Save := I2C_Read (Device, AK8963_RA_CNTL);
-- Power_Down
Set_Mode (Device, Power_Down);
I2C_Write (Device, AK8963_RA_ASTC, 6, True); -- Set SELF bit to True
Dead := Get_Overflow_Status (Device); -- Clears ST1 by reading ST2
Set_Mode (Device, Self_Test, Mode_16bit);
while Retry > 0 loop
exit when Get_Data_Ready (Device);
Retry := Retry - 1;
delay until Clock + Milliseconds (10);
end loop;
if Retry = 0 then
Ret := False;
end if;
Get_Heading (Device, Mx, My, Mz);
Dead := Get_Overflow_Status (Device); -- Clears ST1 by reading ST2
I2C_Write (Device, AK8963_RA_ASTC, 6, False); -- Set SELF bit to False
Set_Mode (Device, Power_Down);
if Mx < AK8963_ST_X_MIN
or else Mx > AK8963_ST_X_MAX
or else My < AK8963_ST_Y_MIN
or else My > AK8963_ST_Y_MAX
or else Mz < AK8963_ST_Z_MIN
or else Mz > AK8963_ST_Z_MAX
then
Ret := False;
end if;
-- Set back the saved config
I2C_Write (Device, AK8963_RA_CNTL, Conf_Save);
return Ret;
end Self_Test;
--------------
-- Set_Mode --
--------------
procedure Set_Mode
(Device : in out AK8963_Device;
Operation_Mode : AK8963_Operation_Mode;
Sampling_Mode : AK8963_Sampling_Mode)
is
Mode : constant Byte :=
AK8963_Operation_Mode'Enum_Rep (Operation_Mode)
or AK8963_Sampling_Mode'Enum_Rep (Sampling_Mode);
begin
I2C_Write (Device, AK8963_RA_CNTL, Mode);
end Set_Mode;
--------------
-- Set_Mode --
--------------
procedure Set_Mode
(Device : in out AK8963_Device;
Operation_Mode : AK8963_Operation_Mode)
is
Mode : constant Byte :=
AK8963_Operation_Mode'Enum_Rep (Operation_Mode);
begin
I2C_Write (Device, AK8963_RA_CNTL, Mode);
end Set_Mode;
--------------------
-- Get_Data_Ready --
--------------------
function Get_Data_Ready (Device : AK8963_Device) return Boolean
is
AK8963_ST1_DRDY_BIT : constant := 0;
begin
return I2C_Read (Device, AK8963_RA_ST1, AK8963_ST1_DRDY_BIT);
end Get_Data_Ready;
-----------------
-- Get_Heading --
-----------------
procedure Get_Heading
(Device : AK8963_Device;
Mx, My, Mz : out Float)
is
Buffer : I2C_Data (1 .. 6);
Status : I2C_Status;
function To_Signed is new
Ada.Unchecked_Conversion (Unsigned_16, Integer_16);
begin
Mem_Read
(Device.I2C_Port.all,
Addr => Device.Address,
Mem_Addr => AK8963_RA_HXL,
Mem_Addr_Size => Memory_Size_8b,
Data => Buffer,
Status => Status);
if Status /= Ok then
Mx := 0.0;
My := 0.0;
Mz := 0.0;
else
Mx :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (2)), 8)
or Unsigned_16 (Buffer (1)))) * MAG_TO_GAUSS;
My :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (4)), 8)
or Unsigned_16 (Buffer (3)))) * MAG_TO_GAUSS;
Mz :=
Float (To_Signed (Shift_Left (Unsigned_16 (Buffer (6)), 8)
or Unsigned_16 (Buffer (5)))) * MAG_TO_GAUSS;
-- Read the sensitivity adjustment data
Mem_Read
(Device.I2C_Port.all,
Addr => Device.Address,
Mem_Addr => AK8963_RA_ASAX,
Mem_Addr_Size => Memory_Size_8b,
Data => Buffer (1 .. 3),
Status => Status);
if Status = Ok then
Mx := Mx * ((Float (Buffer (1)) - 128.0) / 256.0 + 1.0);
My := My * ((Float (Buffer (2)) - 128.0) / 256.0 + 1.0);
Mz := Mz * ((Float (Buffer (3)) - 128.0) / 256.0 + 1.0);
end if;
end if;
end Get_Heading;
-------------------------
-- Get_Overflow_Status --
-------------------------
function Get_Overflow_Status (Device : AK8963_Device) return Boolean
is
AK8963_ST2_HOFL_BIT : constant := 3;
begin
return I2C_Read (Device, AK8963_RA_ST2, AK8963_ST2_HOFL_BIT);
end Get_Overflow_Status;
end AK8963;
|
Fix the read operation for the AK8963 magnitometer.
|
Fix the read operation for the AK8963 magnitometer.
As noted by issue #59
|
Ada
|
bsd-3-clause
|
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
a56c81a497c44e7eb4619fc6e6a02f3479b991c0
|
samples/gperfhash.adb
|
samples/gperfhash.adb
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
--
-- Usage: gperfhash [-i] [-p package] keyword-file
--
-- -i Generate a perfect hash which ignores the case
-- -p package Use <b>package</b> as the name of package (default is <b>gphash</b>)
-- keyword-file The file which contains the keywords, one keyword on each line
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " pragma Preelaborate;");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
-- Re-generate the char position table to ignore the case.
procedure Generate_Char_Position;
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
-- ------------------------------
-- Re-generate the char position table to ignore the case.
-- ------------------------------
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
-- Replace the char position table by ours. The lower case letter are just
-- mapped to the corresponding upper case letter.
if Ignore_Case and I >= 6 and I <= 16 then
if I = 6 then
Generate_Char_Position;
end if;
else
Put_Line (File, L);
end if;
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
Put_Line (File, " H : constant Natural := Hash (S);");
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = "
& "Util.Strings.Transforms.To_Upper_Case (S);");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
raise GNAT.Command_Line.Invalid_Switch;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read the keyword file.");
Ada.Command_Line.Set_Exit_Status (1);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
Log.Error ("-i Generate a perfect hash which ignores the case");
Log.Error ("-p package Use 'package' as the name of package (default is 'gphash')");
Log.Error ("keyword-file The file which contains the keywords, one keyword on each line");
Ada.Command_Line.Set_Exit_Status (1);
end Gperfhash;
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011, 2012, 2013, 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.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
--
-- Usage: gperfhash [-i] [-p package] keyword-file
--
-- -i Generate a perfect hash which ignores the case
-- -p package Use <b>package</b> as the name of package (default is <b>gphash</b>)
-- keyword-file The file which contains the keywords, one keyword on each line
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " pragma Preelaborate;");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
-- Re-generate the char position table to ignore the case.
procedure Generate_Char_Position;
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
-- ------------------------------
-- Re-generate the char position table to ignore the case.
-- ------------------------------
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
Put_Line (File, L);
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
if Ignore_Case then
Put_Line (File, " K : constant String := "
& "Util.Strings.Transforms.To_Upper_Case (S);");
Put_Line (File, " H : constant Natural := Hash (K);");
else
Put_Line (File, " H : constant Natural := Hash (S);");
end if;
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = K;");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
raise GNAT.Command_Line.Invalid_Switch;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read the keyword file.");
Ada.Command_Line.Set_Exit_Status (1);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
Log.Error ("-i Generate a perfect hash which ignores the case");
Log.Error ("-p package Use 'package' as the name of package (default is 'gphash')");
Log.Error ("keyword-file The file which contains the keywords, one keyword on each line");
Ada.Command_Line.Set_Exit_Status (1);
end Gperfhash;
|
Fix the perfect hash example
|
Fix the perfect hash example
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ff2cb9aad47c96c5497d1795f98c2c2e59787fbb
|
src/base/dates/util-dates.adb
|
src/base/dates/util-dates.adb
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013, 2014, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of).
-- ------------------------------
function Time_Of (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => Date.Hour,
Minute => Date.Minute,
Second => Date.Second,
Sub_Second => Date.Sub_Second,
Time_Zone => Date.Time_Zone);
end Time_Of;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Returns true if both dates are on the same day.
-- ------------------------------
function Is_Same_Day (Date1, Date2 : in Ada.Calendar.Time) return Boolean is
Split_Date1 : Date_Record;
Split_Date2 : Date_Record;
begin
Split (Split_Date1, Date1);
Split (Split_Date2, Date2);
return Is_Same_Day (Split_Date1, Split_Date2);
end Is_Same_Day;
function Is_Same_Day (Date1, Date2 : in Date_Record) return Boolean is
begin
return Date1.Year = Date2.Year
and Date1.Month = Date2.Month
and Date1.Month_Day = Date2.Month_Day;
end Is_Same_Day;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 365;
else
return 366;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013, 2014, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of).
-- ------------------------------
function Time_Of (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => Date.Hour,
Minute => Date.Minute,
Second => Date.Second,
Sub_Second => Date.Sub_Second,
Time_Zone => Date.Time_Zone);
end Time_Of;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Returns true if both dates are on the same day.
-- ------------------------------
function Is_Same_Day (Date1, Date2 : in Ada.Calendar.Time) return Boolean is
Split_Date1 : Date_Record;
Split_Date2 : Date_Record;
begin
Split (Split_Date1, Date1);
Split (Split_Date2, Date2);
return Is_Same_Day (Split_Date1, Split_Date2);
end Is_Same_Day;
function Is_Same_Day (Date1, Date2 : in Date_Record) return Boolean is
begin
return Date1.Year = Date2.Year
and Date1.Month = Date2.Month
and Date1.Month_Day = Date2.Month_Day;
end Is_Same_Day;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 366;
else
return 365;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
Fix the Get_Day_Count function
|
Fix the Get_Day_Count function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
19d875dc03c7407704edcee00655b2d0352e1b9a
|
samples/facebook.adb
|
samples/facebook.adb
|
-----------------------------------------------------------------------
-- facebook -- Get information about a Facebook user using the Facebook API
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Util.Strings;
with Util.Beans.Objects;
with Util.Http.Clients;
with Util.Http.Clients.Web;
with Util.Serialize.IO.JSON;
with Mapping;
-- This example shows how to invoke a REST service, retrieve and extract a JSON content
-- into some Ada record. It uses the Facebook Graph API which does not need any
-- authentication (ie, the public Facebook API).
procedure Facebook is
procedure Print (P : in Mapping.Person) is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id));
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username));
Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender));
Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link));
end Print;
Count : constant Natural := Ada.Command_Line.Argument_Count;
-- Mapping for the Person record.
Person_Mapping : aliased Mapping.Person_Mapper.Mapper;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: facebook username ...");
Ada.Text_IO.Put_Line ("Example: facebook btaylor");
return;
end if;
Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID);
Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME);
Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME);
Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME);
Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK);
Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME);
Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER);
Util.Http.Clients.Web.Register;
for I in 1 .. Count loop
declare
URI : constant String := Ada.Command_Line.Argument (I);
P : aliased Mapping.Person;
procedure Get_User is
new Mapping.Rest_Get (Mapping.Person, Mapping.Person_Access,
Mapping.Person_Mapper.Set_Context);
begin
Get_User ("https://graph.facebook.com/" & URI, Person_Mapping'Unchecked_Access, P'Unchecked_Access);
Print (P);
end;
end loop;
end Facebook;
|
-----------------------------------------------------------------------
-- facebook -- Get information about a Facebook user using the Facebook API
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Util.Strings;
with Util.Beans.Objects;
with Util.Http.Clients;
with Util.Http.Clients.Web;
with Util.Http.Rest;
with Util.Serialize.IO.JSON;
with Mapping;
-- This example shows how to invoke a REST service, retrieve and extract a JSON content
-- into some Ada record. It uses the Facebook Graph API which does not need any
-- authentication (ie, the public Facebook API).
procedure Facebook is
procedure Print (P : in Mapping.Person) is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id));
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username));
Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender));
Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link));
end Print;
procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper);
Count : constant Natural := Ada.Command_Line.Argument_Count;
-- Mapping for the Person record.
Person_Mapping : aliased Mapping.Person_Mapper.Mapper;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: facebook username ...");
Ada.Text_IO.Put_Line ("Example: facebook btaylor");
return;
end if;
Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID);
Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME);
Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME);
Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME);
Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK);
Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME);
Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER);
Util.Http.Clients.Web.Register;
for I in 1 .. Count loop
declare
URI : constant String := Ada.Command_Line.Argument (I);
P : aliased Mapping.Person;
begin
Get_User ("https://graph.facebook.com/" & URI,
Person_Mapping'Unchecked_Access,
P'Unchecked_Access);
Print (P);
end;
end loop;
end Facebook;
|
Use the generic Rest_Get operation
|
Use the generic Rest_Get operation
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
b8d9ba44de4ac18530bfc0fcece3796525990b4e
|
mat/src/symbols/mat-symbols-targets.ads
|
mat/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Bfd.Symbols;
with Bfd.Files;
with MAT.Types;
package MAT.Symbols.Targets is
type Target_Symbols is limited record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Bfd.Symbols;
with Bfd.Files;
with Util.Refs;
with MAT.Types;
package MAT.Symbols.Targets is
type Target_Symbols is new Util.Refs.Ref_Entity with record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
end MAT.Symbols.Targets;
|
Use a reference counter for the Target_Symbols
|
Use a reference counter for the Target_Symbols
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
fdc7353caa61f22a17082e638917ffcb260ab388
|
src/el-expressions.adb
|
src/el-expressions.adb
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010, 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
with Util.Beans.Objects;
with Util.Concurrent.Counters;
package body EL.Expressions is
-- ------------------------------
-- Check whether the expression is a holds a constant value.
-- ------------------------------
function Is_Constant (Expr : Expression'Class) return Boolean is
begin
return Expr.Node = null;
end Is_Constant;
-- ------------------------------
-- Returns True if the expression is empty (no constant value and no expression).
-- ------------------------------
function Is_Null (Expr : in Expression'Class) return Boolean is
begin
return Expr.Node = null and Util.Beans.Objects.Is_Null (Expr.Value);
end Is_Null;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return Expr.Value;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the expression string that was parsed.
-- ------------------------------
function Get_Expression (Expr : in Expression) return String is
begin
return Ada.Strings.Unbounded.To_String (Expr.Expr);
end Get_Expression;
-- ------------------------------
-- Set the value of the expression to the given object value.
-- ------------------------------
procedure Set_Value (Expr : in Value_Expression;
Context : in ELContext'Class;
Value : in Object) is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Value expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
Node.Set_Value (Context, Value);
end;
end Set_Value;
-- ------------------------------
-- Returns true if the expression is read-only.
-- ------------------------------
function Is_Readonly (Expr : in Value_Expression;
Context : in ELContext'Class) return Boolean is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
return True;
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Is_Readonly (Context);
end;
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
function Reduce_Expression (Expr : in Expression;
Context : in ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
use Ada.Finalization;
begin
if Expr.Node = null then
return Expr;
end if;
declare
Result : constant Reduction := Expr.Node.Reduce (Context);
begin
return Expression '(Controlled with
Node => Result.Node,
Value => Result.Value,
Expr => Expr.Expr);
end;
end Reduce_Expression;
function Create_ValueExpression (Bean : EL.Objects.Object)
return Value_Expression is
Result : Value_Expression;
begin
Result.Value := Bean;
return Result;
end Create_ValueExpression;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Value_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Value_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a value expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Create a Value_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Value_Expression is
Result : Value_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a value expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Unchecked_Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
-- ------------------------------
-- Create an EL expression from an object.
-- ------------------------------
function Create_Expression (Bean : in EL.Objects.Object)
return Expression is
Result : Expression;
begin
Result.Value := Bean;
return Result;
end Create_Expression;
overriding
function Reduce_Expression (Expr : Value_Expression;
Context : ELContext'Class)
return Value_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end Finalize;
-- ------------------------------
-- Evaluate the method expression and return the object and method
-- binding to execute the method. The result contains a pointer
-- to the bean object and a method binding. The method binding
-- contains the information to invoke the method
-- (such as an access to the function or procedure).
-- Raises the <b>Invalid_Method</b> exception if the method
-- cannot be resolved.
-- ------------------------------
function Get_Method_Info (Expr : in Method_Expression;
Context : in ELContext'Class)
return Method_Info is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Method expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Get_Method_Info (Context);
end;
end Get_Method_Info;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
-- ------------------------------
overriding
function Create_Expression (Expr : in String;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Method_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a method expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
overriding
function Reduce_Expression (Expr : in Method_Expression;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
-- ------------------------------
-- Create a Method_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Method_Expression is
Result : Method_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a method expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Unchecked_Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
end EL.Expressions;
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010, 2011, 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 EL.Expressions.Nodes;
with EL.Expressions.Parser;
with Util.Beans.Objects;
with Util.Concurrent.Counters;
package body EL.Expressions is
-- ------------------------------
-- Check whether the expression is a holds a constant value.
-- ------------------------------
function Is_Constant (Expr : Expression'Class) return Boolean is
begin
return Expr.Node = null;
end Is_Constant;
-- ------------------------------
-- Returns True if the expression is empty (no constant value and no expression).
-- ------------------------------
function Is_Null (Expr : in Expression'Class) return Boolean is
begin
return Expr.Node = null and Util.Beans.Objects.Is_Null (Expr.Value);
end Is_Null;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return Expr.Value;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the expression string that was parsed.
-- ------------------------------
function Get_Expression (Expr : in Expression) return String is
begin
return Ada.Strings.Unbounded.To_String (Expr.Expr);
end Get_Expression;
-- ------------------------------
-- Set the value of the expression to the given object value.
-- ------------------------------
procedure Set_Value (Expr : in Value_Expression;
Context : in ELContext'Class;
Value : in Object) is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Value expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
Node.Set_Value (Context, Value);
end;
end Set_Value;
-- ------------------------------
-- Returns true if the expression is read-only.
-- ------------------------------
function Is_Readonly (Expr : in Value_Expression;
Context : in ELContext'Class) return Boolean is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
return True;
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Is_Readonly (Context);
end;
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
function Reduce_Expression (Expr : in Expression;
Context : in ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
use Ada.Finalization;
begin
if Expr.Node = null then
return Expr;
end if;
declare
Result : constant Reduction := Expr.Node.Reduce (Context);
begin
return Expression '(Controlled with
Node => Result.Node,
Value => Result.Value,
Expr => Expr.Expr);
end;
end Reduce_Expression;
function Create_ValueExpression (Bean : EL.Objects.Object)
return Value_Expression is
Result : Value_Expression;
begin
Result.Value := Bean;
return Result;
end Create_ValueExpression;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Value_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Value_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a value expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Create a Value_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Value_Expression is
Result : Value_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a value expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
-- ------------------------------
-- Create an EL expression from an object.
-- ------------------------------
function Create_Expression (Bean : in EL.Objects.Object)
return Expression is
Result : Expression;
begin
Result.Value := Bean;
return Result;
end Create_Expression;
overriding
function Reduce_Expression (Expr : Value_Expression;
Context : ELContext'Class)
return Value_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end Finalize;
-- ------------------------------
-- Evaluate the method expression and return the object and method
-- binding to execute the method. The result contains a pointer
-- to the bean object and a method binding. The method binding
-- contains the information to invoke the method
-- (such as an access to the function or procedure).
-- Raises the <b>Invalid_Method</b> exception if the method
-- cannot be resolved.
-- ------------------------------
function Get_Method_Info (Expr : in Method_Expression;
Context : in ELContext'Class)
return Method_Info is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Method expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Get_Method_Info (Context);
end;
end Get_Method_Info;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
-- ------------------------------
overriding
function Create_Expression (Expr : in String;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Method_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a method expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
overriding
function Reduce_Expression (Expr : in Method_Expression;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
-- ------------------------------
-- Create a Method_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Method_Expression is
Result : Method_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a method expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
end EL.Expressions;
|
Replace several unecessary 'Unchecked_Access by 'Access
|
Replace several unecessary 'Unchecked_Access by 'Access
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
168f02599df4e71d754365f9a8f0c4a70f9f57f8
|
src/ado-drivers-connections.ads
|
src/ado-drivers-connections.ads
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with Util.Properties;
with Util.Strings;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers.Connections is
use ADO.Statements;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record
Count : Natural := 0;
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new Ada.Finalization.Controlled with private;
type Configuration_Access is access all Configuration'Class;
-- Set the connection URL to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- If the string is invalid or if the driver cannot be found,
-- the Connection_Error exception is raised.
procedure Set_Connection (Controller : in out Configuration;
URI : in String);
-- Set a property on the datasource for the driver.
-- The driver can retrieve the property to configure and open
-- the database connection.
procedure Set_Property (Controller : in out Configuration;
Name : in String;
Value : in String);
-- Get a property from the data source configuration.
-- If the property does not exist, an empty string is returned.
function Get_Property (Controller : in Configuration;
Name : in String) return String;
-- Set the server hostname.
procedure Set_Server (Controller : in out Configuration;
Server : in String);
-- Get the server hostname.
function Get_Server (Controller : in Configuration) return String;
-- Set the server port.
procedure Set_Port (Controller : in out Configuration;
Port : in Natural);
-- Get the server port.
function Get_Port (Controller : in Configuration) return Natural;
-- Get the database name.
function Get_Database (Controller : in Configuration) return String;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : out Database_Connection_Access);
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : out Database_Connection_Access) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
type Configuration is new Ada.Finalization.Controlled with record
URI : Unbounded_String := Null_Unbounded_String;
Server : Unbounded_String := Null_Unbounded_String;
Port : Natural := 0;
Database : Unbounded_String := Null_Unbounded_String;
Properties : Util.Properties.Manager;
Driver : Driver_Access;
end record;
end ADO.Drivers.Connections;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with Util.Properties;
with Util.Strings;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers.Connections is
use ADO.Statements;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record
Count : Natural := 0;
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new Ada.Finalization.Controlled with private;
type Configuration_Access is access all Configuration'Class;
-- Set the connection URL to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- If the string is invalid or if the driver cannot be found,
-- the Connection_Error exception is raised.
procedure Set_Connection (Controller : in out Configuration;
URI : in String);
-- Set a property on the datasource for the driver.
-- The driver can retrieve the property to configure and open
-- the database connection.
procedure Set_Property (Controller : in out Configuration;
Name : in String;
Value : in String);
-- Get a property from the data source configuration.
-- If the property does not exist, an empty string is returned.
function Get_Property (Controller : in Configuration;
Name : in String) return String;
-- Set the server hostname.
procedure Set_Server (Controller : in out Configuration;
Server : in String);
-- Get the server hostname.
function Get_Server (Controller : in Configuration) return String;
-- Set the server port.
procedure Set_Port (Controller : in out Configuration;
Port : in Natural);
-- Get the server port.
function Get_Port (Controller : in Configuration) return Natural;
-- Set the database name.
procedure Set_Database (Controller : in out Configuration;
Database : in String);
-- Get the database name.
function Get_Database (Controller : in Configuration) return String;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : out Database_Connection_Access);
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : out Database_Connection_Access) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
type Configuration is new Ada.Finalization.Controlled with record
URI : Unbounded_String := Null_Unbounded_String;
Server : Unbounded_String := Null_Unbounded_String;
Port : Natural := 0;
Database : Unbounded_String := Null_Unbounded_String;
Properties : Util.Properties.Manager;
Driver : Driver_Access;
end record;
end ADO.Drivers.Connections;
|
Declare the Set_Database procedure
|
Declare the Set_Database procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
169217034a82d013d4a52fb9ba04aea707f3e6f3
|
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;
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;
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;
|
Add some documentation about the AWA commands
|
Add some documentation about the AWA commands
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e32628313b466e673cf2151aa90c12f93952dc29
|
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;
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;
|
-----------------------------------------------------------------------
-- 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";
KEYSTORE_PATH : constant String := "keystore-path";
WALLET_KEY_PATH : constant String := "keystore-masterkey-path";
PASSWORD_FILE_PATH : constant String := "keystore-password-path";
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;
Global_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;
function Get_Application_Config (Context : in Context_Type;
Name : in String) return String;
function Get_Config (Context : in Context_Type;
Name : in String) return String is
(Context.Global_Config.Get (Name));
function Exists (Context : in Context_Type;
Name : in String) return Boolean is
(Context.Global_Config.Exists (Name));
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 support to set the keystore configuration in the global configuration file
|
Add support to set the keystore configuration in the global configuration file
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7ece8717724e9dd2d8488708f721c386a19866b6
|
awa/plugins/awa-mail/src/awa-mail-modules.ads
|
awa/plugins/awa-mail/src/awa-mail-modules.ads
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Maps;
with ASF.Applications;
with AWA.Modules;
with AWA.Events;
with AWA.Mail.Clients;
-- == Documentation ==
-- The *mail* module allows an application to format and send a mail
-- to users. This module does not define any web interface. It provides
-- a set of services and methods to send a mail when an event is
-- received. All this is done through configuration. The module
-- defines a set of specific ASF components to format and prepare the
-- email.
--
-- == Configuration ==
-- The *mail* module needs some properties to configure the SMTP
-- server.
--
-- ||mail.smtp.host||localhost||Defines the SMTP server host name||
-- ||mail.smtp.port||25||Defines the SMTP connection port||
-- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not||
--
-- == Sending an email ==
-- Sending an email when an event is posted can be done by using
-- an XML configuration. Basically, the *mail* module uses the event
-- framework provided by AWA. The XML definition looks like:
--
-- <on-event name="user-register">
-- <action>#{userMail.send}</action>
-- <property name="template">/mail/register-user-message.xhtml</property>
-- </on-event>
--
-- With this definition, the mail template `/mail/register-user-message.xhtml`
-- is formatted by using the event and application context when the
-- `user-register` event is posted.
--
-- @include awa-mail-components.ads
-- @include awa-mail-components-recipients.ads
-- @include awa-mail-components-messages.ads
--
-- == Ada Beans ==
-- @include mail.xml
--
package AWA.Mail.Modules is
NAME : constant String := "mail";
type Mail_Module is new AWA.Modules.Module with private;
type Mail_Module_Access is access all Mail_Module'Class;
-- Initialize the mail module.
overriding
procedure Initialize (Plugin : in out Mail_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 Mail_Module;
Props : in ASF.Applications.Config);
-- Create a new mail message.
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access;
-- Format and send an email.
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class);
-- Get the mail module instance associated with the current application.
function Get_Mail_Module return Mail_Module_Access;
private
type Mail_Module is new AWA.Modules.Module with record
Mailer : AWA.Mail.Clients.Mail_Manager_Access;
end record;
end AWA.Mail.Modules;
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Maps;
with ASF.Applications;
with AWA.Modules;
with AWA.Events;
with AWA.Mail.Clients;
-- == Configuration ==
-- The *mail* module needs some properties to configure the SMTP
-- server.
--
-- ||mail.smtp.host||localhost||Defines the SMTP server host name||
-- ||mail.smtp.port||25||Defines the SMTP connection port||
-- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not||
--
-- == Sending an email ==
-- Sending an email when an event is posted can be done by using
-- an XML configuration. Basically, the *mail* module uses the event
-- framework provided by AWA. The XML definition looks like:
--
-- <on-event name="user-register">
-- <action>#{userMail.send}</action>
-- <property name="template">/mail/register-user-message.xhtml</property>
-- </on-event>
--
-- With this definition, the mail template `/mail/register-user-message.xhtml`
-- is formatted by using the event and application context when the
-- `user-register` event is posted.
--
-- @include awa-mail-components.ads
-- @include awa-mail-components-recipients.ads
-- @include awa-mail-components-messages.ads
--
-- == Ada Beans ==
-- @include mail.xml
--
package AWA.Mail.Modules is
NAME : constant String := "mail";
type Mail_Module is new AWA.Modules.Module with private;
type Mail_Module_Access is access all Mail_Module'Class;
-- Initialize the mail module.
overriding
procedure Initialize (Plugin : in out Mail_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 Mail_Module;
Props : in ASF.Applications.Config);
-- Create a new mail message.
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access;
-- Format and send an email.
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class);
-- Get the mail module instance associated with the current application.
function Get_Mail_Module return Mail_Module_Access;
private
type Mail_Module is new AWA.Modules.Module with record
Mailer : AWA.Mail.Clients.Mail_Manager_Access;
end record;
end AWA.Mail.Modules;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7c472e27311c5f9b2c2d4b35d06a5ba027b62dea
|
testcases/driver_connections/sqlite/connect.ads
|
testcases/driver_connections/sqlite/connect.ads
|
-- Used for all testcases for SQLite driver
with AdaBase.Driver.Base.SQLite;
with AdaBase.Statement.Base.SQLite;
package Connect is
-- All specific drivers renamed to "Database_Driver"
subtype Database_Driver is AdaBase.Driver.Base.SQLite.SQLite_Driver;
-- subtype Stmt_Type is AdaBase.Statement.Base.SQLite.SQLite_statement;
-- subtype Stmt_Type_access is
-- AdaBase.Statement.Base.SQLite.SQLite_statement_access;
DR : Database_Driver;
procedure connect_database;
end Connect;
|
-- Used for all testcases for SQLite driver
with AdaBase.Driver.Base.SQLite;
with AdaBase.Statement.Base.SQLite;
package Connect is
-- All specific drivers renamed to "Database_Driver"
subtype Database_Driver is AdaBase.Driver.Base.SQLite.SQLite_Driver;
subtype Stmt_Type is AdaBase.Statement.Base.SQLite.SQLite_statement;
subtype Stmt_Type_access is
AdaBase.Statement.Base.SQLite.SQLite_statement_access;
DR : Database_Driver;
procedure connect_database;
end Connect;
|
enable prep stmt support in sqlite testcases
|
enable prep stmt support in sqlite testcases
|
Ada
|
isc
|
jrmarino/AdaBase
|
35230c9e7d2a0cc12a7639fcc9cd5bbddfed0fe1
|
src/gen-commands-page.adb
|
src/gen-commands-page.adb
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
package body Gen.Commands.Page 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;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Get_Argument;
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout);
return "layout";
end Get_Layout;
Name : constant String := Get_Name;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
package body Gen.Commands.Page 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;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Get_Argument;
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Info ("Layout file {0} not found.", Layout);
return Layout;
end Get_Layout;
Name : constant String := Get_Name;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
Allow to use a layout that is located outside of the user WEB-INF directory
|
Allow to use a layout that is located outside of the user WEB-INF directory
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
ea17d8417bf14f242d5d3ef892b59511835bb422
|
src/wiki-streams.ads
|
src/wiki-streams.ads
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- 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.
-----------------------------------------------------------------------
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams is
type Input_Stream is limited interface;
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
procedure Read (Input : in out Input_Stream;
Char : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
procedure Write (Stream : in out Output_Stream;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Stream : in out Output_Stream;
Char : in Wide_Wide_Character) is abstract;
end Wiki.Streams;
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- 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.
-----------------------------------------------------------------------
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams is
pragma Preelaborate;
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
procedure Read (Input : in out Input_Stream;
Char : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
procedure Write (Stream : in out Output_Stream;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Stream : in out Output_Stream;
Char : in Wide_Wide_Character) is abstract;
end Wiki.Streams;
|
Declare Input_Stream_Access type
|
Declare Input_Stream_Access type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
acefded802857d09186a72a402a1eb21450c6d22
|
src/wiki-strings.adb
|
src/wiki-strings.adb
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016, 2017, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Strings is
-- ------------------------------
-- Search for the first occurrence of the character in the builder and
-- starting after the from index. Returns the index of the first occurence or 0.
-- ------------------------------
function Index (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural is
function Find (Content : in WString) return Natural;
function Find (Content : in WString) return Natural is
begin
for I in Content'Range loop
if Content (I) = Char then
return I;
end if;
end loop;
return 0;
end Find;
function Find_Builder is
new Wide_Wide_Builders.Find (Find);
begin
return Find_Builder (Source, From);
end Index;
-- ------------------------------
-- Find the last position of the character in the string and starting
-- at the given position. Stop at the first character different than `Char`.
-- ------------------------------
function Last_Position (Source : in Bstring;
Char : in WChar;
From : in Positive := 1) return Natural is
function Find (Content : in WString) return Natural;
function Find (Content : in WString) return Natural is
begin
for I in Content'Range loop
if Content (I) /= Char then
return I;
end if;
end loop;
return 0;
end Find;
function Find_Builder is
new Wide_Wide_Builders.Find (Find);
begin
return Find_Builder (Source, From);
end Last_Position;
-- ------------------------------
-- Count the the number of consecutive occurence of the given character
-- and starting at the given position.
-- ------------------------------
function Count_Occurence (Source : in Bstring;
Char : in WChar;
From : in Positive := 1) return Natural is
Pos : constant Natural := Last_Position (Source, Char, From);
begin
if Pos > From then
return Pos - From;
else
return 0;
end if;
end Count_Occurence;
function Skip_Spaces (Source : in Bstring;
From : in Positive;
Last : in Positive) return Positive is
Pos : Positive := From;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Element (Source, Pos)) loop
Pos := Pos + 1;
end loop;
return Pos;
end Skip_Spaces;
end Wiki.Strings;
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016, 2017, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Strings is
-- ------------------------------
-- Search for the first occurrence of the character in the builder and
-- starting after the from index. Returns the index of the first occurence or 0.
-- ------------------------------
function Index (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural is
function Find (Content : in WString) return Natural;
function Find (Content : in WString) return Natural is
begin
for I in Content'Range loop
if Content (I) = Char then
return I;
end if;
end loop;
return 0;
end Find;
function Find_Builder is
new Wide_Wide_Builders.Find (Find);
begin
return Find_Builder (Source, From);
end Index;
-- ------------------------------
-- Find the last position of the character in the string and starting
-- at the given position. Stop at the first character different than `Char`.
-- ------------------------------
function Last_Position (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural is
function Find (Content : in WString) return Natural;
function Find (Content : in WString) return Natural is
begin
for I in Content'Range loop
if Content (I) /= Char then
return I;
end if;
end loop;
return 0;
end Find;
function Find_Builder is
new Wide_Wide_Builders.Find (Find);
begin
return Find_Builder (Source, From);
end Last_Position;
-- ------------------------------
-- Count the the number of consecutive occurence of the given character
-- and starting at the given position.
-- ------------------------------
function Count_Occurence (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural is
Pos : constant Natural := Last_Position (Source, Char, From);
begin
if Pos > From then
return Pos - From;
else
return 0;
end if;
end Count_Occurence;
function Count_Occurence (Source : in WString;
Char : in WChar;
From : in Positive := 1) return Natural is
Pos : Positive := From;
begin
while Pos <= Source'Last and then Source (Pos) = Char loop
Pos := Pos + 1;
end loop;
return Pos - From;
end Count_Occurence;
function Skip_Spaces (Source : in BString;
From : in Positive;
Last : in Positive) return Positive is
Pos : Positive := From;
begin
while Pos <= Last and then Helpers.Is_Space_Or_Newline (Element (Source, Pos)) loop
Pos := Pos + 1;
end loop;
return Pos;
end Skip_Spaces;
procedure Scan_Line_Fragment (Source : in BString;
Process : not null
access procedure (Text : in WString;
Offset : in Natural)) is
Offset : Natural := 0;
procedure Parse_Line_Fragment (Content : in Wiki.Strings.WString) is
begin
Process (Content, Offset);
Offset := Offset + Content'Length;
end Parse_Line_Fragment;
procedure Parse_Line_Fragment is
new Wiki.Strings.Wide_Wide_Builders.Get (Parse_Line_Fragment);
pragma Inline (Parse_Line_Fragment);
begin
Parse_Line_Fragment (Source);
end Scan_Line_Fragment;
end Wiki.Strings;
|
Add new operations for the strings
|
Add new operations for the strings
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f80c276e70c47d3d1f653616921b2ce07217eeeb
|
awa/plugins/awa-tags/src/awa-tags-modules.adb
|
awa/plugins/awa-tags/src/awa-tags-modules.adb
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ADO.Sessions.Entities;
with ADO.Statements;
with ADO.Queries;
with ADO.SQL;
with Security.Permissions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Users.Models;
with AWA.Tags.Models;
with AWA.Tags.Beans;
with AWA.Tags.Components;
with Util.Log.Loggers;
package body AWA.Tags.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tags.Module");
package Register is new AWA.Modules.Beans (Module => Tag_Module,
Module_Access => Tag_Module_Access);
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- ------------------------------
-- Initialize the tags module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-tags module");
App.Add_Components (AWA.Tags.Components.Definition);
-- Register the tag list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_List_Bean'Access);
-- Register the tag search bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Search_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Search_Bean'Access);
-- Register the tag info list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Info_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Info_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the tags module.
-- ------------------------------
function Get_Tag_Module return Tag_Module_Access is
function Get is new AWA.Modules.Get (Tag_Module, Tag_Module_Access, NAME);
begin
return Get;
end Get_Tag_Module;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
-- ------------------------------
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} add tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Add_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
-- ------------------------------
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Remove_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Remove_Tag;
-- ------------------------------
-- Remove the tags defined by the <tt>Deleted</tt> tag list and add the tags defined
-- in the <tt>Added</tt> tag list. The tags are associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove or add the tag.
-- ------------------------------
procedure Update_Tags (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Added : in Util.Strings.Vectors.Vector;
Deleted : in Util.Strings.Vectors.Vector) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Iter : Util.Strings.Vectors.Cursor;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Delete the tags that have been removed.
Iter := Deleted.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Remove_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
-- And add the new ones.
Iter := Added.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} adds tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Add_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
Ctx.Commit;
end Update_Tags;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.Queries.Context;
Tag_Info : AWA.Tags.Models.Tag_Ref;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
begin
Query.Set_Query (AWA.Tags.Models.Query_Check_Tag);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
-- Build the query.
Stmt.Bind_Param (Name => "entity_type", Value => Entity_Type);
Stmt.Bind_Param (Name => "entity_id", Value => Id);
Stmt.Bind_Param (Name => "tag", Value => Tag);
-- Run the query.
Stmt.Execute;
if not Stmt.Has_Elements then
-- The tag is not defined in the database.
-- Create it and link it to the entity.
Tag_Info.Set_Name (Tag);
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Info.Save (Session);
Tag_Link.Save (Session);
elsif Stmt.Is_Null (1) then
-- The tag is defined but the entity is not linked with it.
Tag_Info.Set_Id (Stmt.Get_Identifier (0));
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Link.Save (Session);
end if;
end;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.SQL.Query;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_tag AS tag ON tag.id = o.tag_id");
Query.Set_Filter ("tag.name = :tag AND o.for_entity_id = :entity_id "
& "AND o.entity_type = :entity_type");
-- Build the query.
Query.Bind_Param (Name => "entity_type", Value => Entity_Type);
Query.Bind_Param (Name => "entity_id", Value => Id);
Query.Bind_Param (Name => "tag", Value => Tag);
Tag_Link.Find (Session, Query, Found);
if Found then
Tag_Link.Delete (Session);
end if;
end Remove_Tag;
-- ------------------------------
-- Find the tag identifier associated with the given tag.
-- Return NO_IDENTIFIER if there is no such tag.
-- ------------------------------
procedure Find_Tag_Id (Session : in out ADO.Sessions.Session'Class;
Tag : in String;
Result : out ADO.Identifier) is
begin
if Tag'Length = 0 then
Result := ADO.NO_IDENTIFIER;
else
declare
Query : ADO.SQL.Query;
Found : Boolean;
Tag_Info : AWA.Tags.Models.Tag_Ref;
begin
Query.Set_Filter ("o.name = ?");
Query.Bind_Param (1, Tag);
Tag_Info.Find (Session => Session,
Query => Query,
Found => Found);
if not Found then
Result := ADO.NO_IDENTIFIER;
else
Result := Tag_Info.Get_Id;
end if;
end;
end if;
end Find_Tag_Id;
end AWA.Tags.Modules;
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- 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 ADO.Sessions.Entities;
with ADO.Statements;
with ADO.Queries;
with ADO.SQL;
with Security.Permissions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Users.Models;
with AWA.Tags.Models;
with AWA.Tags.Beans;
with AWA.Tags.Components;
with Util.Log.Loggers;
package body AWA.Tags.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tags.Module");
package Register is new AWA.Modules.Beans (Module => Tag_Module,
Module_Access => Tag_Module_Access);
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- ------------------------------
-- Initialize the tags module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-tags module");
App.Add_Components (AWA.Tags.Components.Definition);
-- Register the tag list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_List_Bean'Access);
-- Register the tag search bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Search_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Search_Bean'Access);
-- Register the tag info list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Info_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Info_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the tags module.
-- ------------------------------
function Get_Tag_Module return Tag_Module_Access is
function Get is new AWA.Modules.Get (Tag_Module, Tag_Module_Access, NAME);
begin
return Get;
end Get_Tag_Module;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
-- ------------------------------
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} add tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Add_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
-- ------------------------------
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Remove_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Remove_Tag;
-- ------------------------------
-- Remove the tags defined by the <tt>Deleted</tt> tag list and add the tags defined
-- in the <tt>Added</tt> tag list. The tags are associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove or add the tag.
-- ------------------------------
procedure Update_Tags (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Added : in Util.Strings.Vectors.Vector;
Deleted : in Util.Strings.Vectors.Vector) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Iter : Util.Strings.Vectors.Cursor;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Delete the tags that have been removed.
Iter := Deleted.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Remove_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
-- And add the new ones.
Iter := Added.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} adds tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Add_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
Ctx.Commit;
end Update_Tags;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.Queries.Context;
Tag_Info : AWA.Tags.Models.Tag_Ref;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
begin
Query.Set_Query (AWA.Tags.Models.Query_Check_Tag);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
-- Build the query.
Stmt.Bind_Param (Name => "entity_type", Value => Entity_Type);
Stmt.Bind_Param (Name => "entity_id", Value => Id);
Stmt.Bind_Param (Name => "tag", Value => Tag);
-- Run the query.
Stmt.Execute;
if not Stmt.Has_Elements then
-- The tag is not defined in the database.
-- Create it and link it to the entity.
Tag_Info.Set_Name (Tag);
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Info.Save (Session);
Tag_Link.Save (Session);
elsif Stmt.Is_Null (1) then
-- The tag is defined but the entity is not linked with it.
Tag_Info.Set_Id (Stmt.Get_Identifier (0));
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Link.Save (Session);
end if;
end;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.SQL.Query;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_tag AS tag ON tag.id = o.tag_id");
Query.Set_Filter ("tag.name = :tag AND o.for_entity_id = :entity_id "
& "AND o.entity_type = :entity_type");
-- Build the query.
Query.Bind_Param (Name => "entity_type", Value => Entity_Type);
Query.Bind_Param (Name => "entity_id", Value => Id);
Query.Bind_Param (Name => "tag", Value => Tag);
Tag_Link.Find (Session, Query, Found);
if Found then
Tag_Link.Delete (Session);
end if;
end Remove_Tag;
-- ------------------------------
-- Find the tag identifier associated with the given tag.
-- Return NO_IDENTIFIER if there is no such tag.
-- ------------------------------
procedure Find_Tag_Id (Session : in out ADO.Sessions.Session'Class;
Tag : in String;
Result : out ADO.Identifier) is
begin
if Tag'Length = 0 then
Result := ADO.NO_IDENTIFIER;
else
declare
Query : ADO.SQL.Query;
Found : Boolean;
Tag_Info : AWA.Tags.Models.Tag_Ref;
begin
Query.Set_Filter ("o.name = ?");
Query.Bind_Param (1, Tag);
Tag_Info.Find (Session => Session,
Query => Query,
Found => Found);
if not Found then
Result := ADO.NO_IDENTIFIER;
else
Result := Tag_Info.Get_Id;
end if;
end;
end if;
end Find_Tag_Id;
end AWA.Tags.Modules;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5f20993169c44547f4146a96a4cabbfd0aa08ace
|
awa/src/awa-events.ads
|
awa/src/awa-events.ads
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
with AWA.Index_Arrays;
-- == AWA Events ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- with AWA.Events.Definition;
-- ...
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- with AWA.Events;
-- ...
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- === Data Model ===
-- [images/awa_events_model.png]
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
package Event_Arrays is new AWA.Index_Arrays (Event_Index, String);
use type Event_Arrays.Element_Type_Access;
subtype Name_Access is Event_Arrays.Element_Type_Access;
generic
package Definition renames Event_Arrays.Definition;
-- Exception raised if an event name is not found.
Not_Found : exception renames Event_Arrays.Not_Found;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Event_Arrays.Invalid_Index;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE;
end record;
-- The index of the last event definition.
-- Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Name_Access
renames Event_Arrays.Get_Element;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012, 2015, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with Util.Properties;
with ADO.Objects;
with ADO.Sessions;
with AWA.Index_Arrays;
-- == AWA Events ==
-- The `AWA.Events` package defines an event framework for modules to post
-- events and have Ada bean methods be invoked when these events are dispatched.
-- Subscription to events is done through configuration files. This allows to
-- configure the modules and integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the
-- `Definition` package. This is a static definition of the event. Each event
-- is given a unique name.
--
-- with AWA.Events.Definition;
-- ...
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that
-- a particular action occurred. The module creates the event instance of
-- type `Module_Event` and populates that event with useful properties for
-- event receivers.
--
-- with AWA.Events;
-- ...
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure
-- the event manager to dispatch the event to an Ada bean event action.
-- The Ada bean is an object that must implement a procedure that matches
-- the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean;
-- Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and
-- the event together. The action is specified using an EL Method Expression
-- (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The `AWA.Events` framework posts events on queues and it uses a dispatcher
-- to process them. There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted.
-- The task which posts the event invokes the Ada bean action.
-- In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event
-- is put in an event queue. A dispatcher task processes the event and
-- invokes the action method at a later time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue
-- are lost.
--
-- * A persistent event queue manages the event in a similar way as the
-- FIFO queue but saves them in the database. If the application is
-- stopped, events that have not yet been processed will be dispatched
-- when the application is started again.
--
-- === Data Model ===
-- [images/awa_events_model.png]
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
package Event_Arrays is new AWA.Index_Arrays (Event_Index, String);
use type Event_Arrays.Element_Type_Access;
subtype Name_Access is Event_Arrays.Element_Type_Access;
generic
package Definition renames Event_Arrays.Definition;
-- Exception raised if an event name is not found.
Not_Found : exception renames Event_Arrays.Not_Found;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String)
return Event_Index renames Event_Arrays.Find;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event
and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Set the parameters of the message.
procedure Set_Parameters (Event : in out Module_Event;
Parameters : in Util.Beans.Objects.Maps.Map);
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Set the database entity associated with the event.
procedure Set_Entity (Event : in out Module_Event;
Entity : in ADO.Objects.Object_Ref'Class;
Session : in ADO.Sessions.Session'Class);
-- Copy the event properties to the map passed in `Into`.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event
and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Event_Arrays.Invalid_Index;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE;
end record;
-- The index of the last event definition.
-- Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Name_Access
renames Event_Arrays.Get_Element;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
Add Set_Entity and Set_Parameters operations
|
Add Set_Entity and Set_Parameters operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ff5a0c9107f89944e46a3d70344cbca588644eb0
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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.Events.Faces.Actions;
with ADO.Sessions;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Send;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Send;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
end AWA.Workspaces.Beans;
|
Implement the Load procedure
|
Implement the Load procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
014199c838627f0d401cbb1853f558e65ee059ec
|
src/security-filters.ads
|
src/security-filters.ads
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Permissions;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Security.Permissions.Permission_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Security.Permissions.Permission_Manager_Access := null;
end record;
end Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Permissions;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Security.Permissions.Permission_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Security.Permissions.Permission_Manager_Access := null;
end record;
end Security.Filters;
|
Mark initialize as overriding
|
Mark initialize as overriding
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
3353d1bd8dcbeece0fa59b162286b5befdafec3c
|
src/orka/interface/orka-rendering-fences.ads
|
src/orka/interface/orka-rendering-fences.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 GL.Fences;
generic
type Index_Type is mod <>;
Maximum_Wait : Duration := 0.010;
package Orka.Rendering.Fences is
pragma Preelaborate;
type Buffer_Fence is tagged private;
type Fence_Status is (Not_Initialized, Signaled, Not_Signaled);
function Create_Buffer_Fence return Buffer_Fence;
procedure Prepare_Index (Object : in out Buffer_Fence; Status : out Fence_Status);
-- Perform a client wait sync for the fence corresponding to the
-- current index
procedure Advance_Index (Object : in out Buffer_Fence);
-- Set a fence for the corresponding index and then increment it
private
type Fence_Array is array (Index_Type) of GL.Fences.Fence;
type Buffer_Fence is tagged record
Fences : Fence_Array;
Index : Index_Type;
end record;
end Orka.Rendering.Fences;
|
-- 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.
private with GL.Fences;
generic
type Index_Type is mod <>;
Maximum_Wait : Duration := 0.010;
package Orka.Rendering.Fences is
pragma Preelaborate;
type Buffer_Fence is tagged private;
type Fence_Status is (Not_Initialized, Signaled, Not_Signaled);
function Create_Buffer_Fence return Buffer_Fence;
procedure Prepare_Index (Object : in out Buffer_Fence; Status : out Fence_Status);
-- Perform a client wait sync for the fence corresponding to the
-- current index
procedure Advance_Index (Object : in out Buffer_Fence);
-- Set a fence for the corresponding index and then increment it
private
type Fence_Array is array (Index_Type) of GL.Fences.Fence;
type Buffer_Fence is tagged record
Fences : Fence_Array;
Index : Index_Type;
end record;
end Orka.Rendering.Fences;
|
Use private with for with'ed unit in Orka.Rendering.Fences
|
orka: Use private with for with'ed unit in Orka.Rendering.Fences
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
c0cfaf46c7528ac22b0e3c205e10ad1da244e938
|
src/util-log-loggers.ads
|
src/util-log-loggers.ads
|
-----------------------------------------------------------------------
-- Logs -- Utility Log Package
-- Copyright (C) 2006, 2008, 2009 Free Software Foundation, Inc.
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Log.Appenders;
with Util.Properties;
with Ada.Finalization;
package Util.Log.Loggers is
use Ada.Exceptions;
use Ada.Strings.Unbounded;
-- The logger identifies and configures the log produced
-- by a component that uses it. The logger has a name
-- which can be printed in the log outputs. The logger instance
-- contains a log level which can be used to control the level of
-- logs.
type Logger is tagged limited private;
-- Create a logger with the given name.
function Create (Name : in String) return Logger;
-- Create a logger with the given name and use the specified level.
function Create (Name : in String;
Level : in Level_Type) return Logger;
-- Initialize the logger and create a logger with the given name.
function Create (Name : in String;
Config : in String) return Logger;
-- Change the log level
procedure Set_Level (Log : in out Logger;
Level : in Level_Type);
-- Get the log level.
function Get_Level (Log : in Logger) return Level_Type;
-- Get the log level name.
function Get_Level_Name (Log : in Logger) return String;
procedure Print (Log : in Logger;
Level : in Level_Type;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in Unbounded_String;
Arg3 : in String := "");
procedure Info (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Info (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in String := "";
Arg3 : in String := "");
procedure Warn (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Error (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Error (Log : in Logger'Class;
Message : in String;
E : in Exception_Occurrence);
-- Set the appender that will handle the log events
procedure Set_Appender (Log : in out Logger'Class;
Appender : in Util.Log.Appenders.Appender_Access);
-- Initialize the log environment with the property file.
procedure Initialize (Name : in String);
-- Initialize the log environment with the properties.
procedure Initialize (Properties : in Util.Properties.Manager);
private
type Logger_Info;
type Logger_Info_Access is access all Logger_Info;
type Logger_Info is record
Next_Logger : Logger_Info_Access;
Prev_Logger : Logger_Info_Access;
Level : Level_Type := INFO_LEVEL;
Name : Unbounded_String;
Appender : Util.Log.Appenders.Appender_Access;
end record;
type Logger is new Ada.Finalization.Limited_Controlled with record
Name : Unbounded_String;
Instance : Logger_Info_Access;
end record;
-- Finalize the logger and flush the associated appender
procedure Finalize (Log : in out Logger);
end Util.Log.Loggers;
|
-----------------------------------------------------------------------
-- Logs -- Utility Log Package
-- Copyright (C) 2006, 2008, 2009, 2011 Free Software Foundation, Inc.
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Log.Appenders;
with Util.Properties;
with Ada.Finalization;
package Util.Log.Loggers is
use Ada.Exceptions;
use Ada.Strings.Unbounded;
-- The logger identifies and configures the log produced
-- by a component that uses it. The logger has a name
-- which can be printed in the log outputs. The logger instance
-- contains a log level which can be used to control the level of
-- logs.
type Logger is tagged limited private;
type Logger_Access is access constant Logger'Class;
-- Create a logger with the given name.
function Create (Name : in String) return Logger;
-- Create a logger with the given name and use the specified level.
function Create (Name : in String;
Level : in Level_Type) return Logger;
-- Initialize the logger and create a logger with the given name.
function Create (Name : in String;
Config : in String) return Logger;
-- Change the log level
procedure Set_Level (Log : in out Logger;
Level : in Level_Type);
-- Get the log level.
function Get_Level (Log : in Logger) return Level_Type;
-- Get the log level name.
function Get_Level_Name (Log : in Logger) return String;
procedure Print (Log : in Logger;
Level : in Level_Type;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in String := "";
Arg3 : in String := "");
procedure Debug (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in Unbounded_String;
Arg3 : in String := "");
procedure Info (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Info (Log : in Logger'Class;
Message : in String;
Arg1 : in Unbounded_String;
Arg2 : in String := "";
Arg3 : in String := "");
procedure Warn (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Error (Log : in Logger'Class;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
procedure Error (Log : in Logger'Class;
Message : in String;
E : in Exception_Occurrence);
-- Set the appender that will handle the log events
procedure Set_Appender (Log : in out Logger'Class;
Appender : in Util.Log.Appenders.Appender_Access);
-- Initialize the log environment with the property file.
procedure Initialize (Name : in String);
-- Initialize the log environment with the properties.
procedure Initialize (Properties : in Util.Properties.Manager);
private
type Logger_Info;
type Logger_Info_Access is access all Logger_Info;
type Logger_Info is record
Next_Logger : Logger_Info_Access;
Prev_Logger : Logger_Info_Access;
Level : Level_Type := INFO_LEVEL;
Name : Unbounded_String;
Appender : Util.Log.Appenders.Appender_Access;
end record;
type Logger is new Ada.Finalization.Limited_Controlled with record
Name : Unbounded_String;
Instance : Logger_Info_Access;
end record;
-- Finalize the logger and flush the associated appender
procedure Finalize (Log : in out Logger);
end Util.Log.Loggers;
|
Define the Logger_Access type
|
Define the Logger_Access type
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
86ccf7f632b36e466fd87ed782e71af34511dba3
|
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;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- 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;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- 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 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);
-- 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.Streams;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- 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;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- 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 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);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Use Wiki.Format_Map type
|
Use Wiki.Format_Map type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ab494cff94e82a777443606d28930a670cc20f14
|
src/ado-schemas-entities.adb
|
src/ado-schemas-entities.adb
|
-----------------------------------------------------------------------
-- ado-schemas-entities -- Entity types cache
-- 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.Log.Loggers;
with ADO.SQL;
with ADO.Statements;
with ADO.Model;
package body ADO.Schemas.Entities is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Schemas.Entities");
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Table : in Class_Mapping_Access) return ADO.Entity_Type is
begin
return Find_Entity_Type (Cache, Table.Table);
end Find_Entity_Type;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Name : in Util.Strings.Name_Access) return ADO.Entity_Type is
Pos : constant Entity_Map.Cursor := Cache.Entities.Find (Name.all);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name.all);
raise No_Entity_Type with "No entity type associated with table " & Name.all;
end if;
return Entity_Type (Entity_Map.Element (Pos));
end Find_Entity_Type;
-- ------------------------------
-- Initialize the entity cache by reading the database entity table.
-- ------------------------------
procedure Initialize (Cache : in out Entity_Cache;
Session : in out ADO.Sessions.Session'Class) is
use type Ada.Containers.Count_Type;
Query : ADO.SQL.Query;
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (ADO.Model.ENTITY_TYPE_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant ADO.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (0));
Name : constant String := Stmt.Get_String (1);
begin
Cache.Entities.Insert (Key => Name, New_Item => Id);
end;
Stmt.Next;
end loop;
exception
when others =>
null;
end Initialize;
end ADO.Schemas.Entities;
|
-----------------------------------------------------------------------
-- ado-schemas-entities -- Entity types cache
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ADO.SQL;
with ADO.Statements;
with ADO.Model;
package body ADO.Schemas.Entities is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Schemas.Entities");
-- ------------------------------
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
-- ------------------------------
overriding
function Expand (Instance : in out Entity_Cache;
Name : in String) return ADO.Parameters.Parameter is
Pos : constant Entity_Map.Cursor := Instance.Entities.Find (Name);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name);
raise No_Entity_Type with "No entity type associated with table " & Name;
end if;
return ADO.Parameters.Parameter '(T => ADO.Parameters.T_INTEGER,
Len => 0, Value_Len => 0, Position => 0,
Name => "",
Num => Entity_Type'Pos (Entity_Map.Element (Pos)));
end Expand;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Table : in Class_Mapping_Access) return ADO.Entity_Type is
begin
return Find_Entity_Type (Cache, Table.Table);
end Find_Entity_Type;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Name : in Util.Strings.Name_Access) return ADO.Entity_Type is
Pos : constant Entity_Map.Cursor := Cache.Entities.Find (Name.all);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name.all);
raise No_Entity_Type with "No entity type associated with table " & Name.all;
end if;
return Entity_Type (Entity_Map.Element (Pos));
end Find_Entity_Type;
-- ------------------------------
-- Initialize the entity cache by reading the database entity table.
-- ------------------------------
procedure Initialize (Cache : in out Entity_Cache;
Session : in out ADO.Sessions.Session'Class) is
use type Ada.Containers.Count_Type;
Query : ADO.SQL.Query;
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (ADO.Model.ENTITY_TYPE_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant ADO.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (0));
Name : constant String := Stmt.Get_String (1);
begin
Cache.Entities.Insert (Key => Name, New_Item => Id);
end;
Stmt.Next;
end loop;
exception
when others =>
null;
end Initialize;
end ADO.Schemas.Entities;
|
Implement the Expand function
|
Implement the Expand function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
ea43f0638474b60165c6fbe57e4db9968a518087
|
awa/awaunit/awa-tests-helpers-users.adb
|
awa/awaunit/awa-tests-helpers-users.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use type AWA.Users.Principals.Principal_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users");
MAX_USERS : constant Positive := 10;
Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- ------------------------------
-- Simulate a user login in the given service context.
-- ------------------------------
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
-- Keep track of the Principal instance so that Tear_Down will release it.
-- Most tests will call Login but don't call Logout because there is no real purpose
-- for the test in doing that and it allows to keep the unit test simple. This creates
-- memory leak because the Principal instance is not freed.
for I in Logged_Users'Range loop
if Logged_Users (I) = null then
Logged_Users (I) := Principal;
exit;
end if;
end loop;
end Login;
-- ------------------------------
-- Setup the context and security context to simulate an anonymous user.
-- ------------------------------
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Context.Set_Context (App, null);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => null);
end Anonymous;
overriding
procedure Finalize (Principal : in out Test_User) is
begin
Free (Principal.Principal);
end Finalize;
-- ------------------------------
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
-- ------------------------------
procedure Tear_Down is
begin
for I in Logged_Users'Range loop
if Logged_Users (I) /= null then
Free (Logged_Users (I));
end if;
end loop;
end Tear_Down;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with ASF.Responses.Mockup;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use type AWA.Users.Principals.Principal_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users");
MAX_USERS : constant Positive := 10;
Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- ------------------------------
-- Simulate a user login in the given service context.
-- ------------------------------
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
-- Keep track of the Principal instance so that Tear_Down will release it.
-- Most tests will call Login but don't call Logout because there is no real purpose
-- for the test in doing that and it allows to keep the unit test simple. This creates
-- memory leak because the Principal instance is not freed.
for I in Logged_Users'Range loop
if Logged_Users (I) = null then
Logged_Users (I) := Principal;
exit;
end if;
end loop;
end Login;
-- ------------------------------
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
-- ------------------------------
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request) is
User : Test_User;
Reply : ASF.Responses.Mockup.Response;
begin
Create_User (User, Email);
ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
end Login;
-- ------------------------------
-- Setup the context and security context to simulate an anonymous user.
-- ------------------------------
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Context.Set_Context (App, null);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => null);
end Anonymous;
overriding
procedure Finalize (Principal : in out Test_User) is
begin
Free (Principal.Principal);
end Finalize;
-- ------------------------------
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
-- ------------------------------
procedure Tear_Down is
begin
for I in Logged_Users'Range loop
if Logged_Users (I) /= null then
Free (Logged_Users (I));
end if;
end loop;
end Tear_Down;
end AWA.Tests.Helpers.Users;
|
Implement the Login procedure to simulate an authentication on the web server
|
Implement the Login procedure to simulate an authentication on the web server
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
193eb162c074b37f96746f712d9d9936fc3833b2
|
mat/src/mat-consoles.adb
|
mat/src/mat-consoles.adb
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles is
-- ------------------------------
-- Print the title for the given field and setup the associated field size.
-- ------------------------------
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive) is
begin
Console.Sizes (Field) := Length;
if Console.Field_Count >= 1 then
Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count))
+ Console.Sizes (Console.Fields (Console.Field_Count));
else
Console.Cols (Field) := 1;
end if;
Console.Field_Count := Console.Field_Count + 1;
Console.Fields (Console.Field_Count) := Field;
Console_Type'Class (Console).Print_Title (Field, Title);
end Print_Title;
-- ------------------------------
-- Format the address and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr) is
Value : constant String := MAT.Types.Hex_Image (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the size and print it for the given field.
-- ------------------------------
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size) is
Value : constant String := MAT.Types.Target_Size'Image (Size);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Size;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer) is
Val : constant String := Integer'Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val);
end Print_Field;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value));
end Print_Field;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles is
-- ------------------------------
-- Print the title for the given field and setup the associated field size.
-- ------------------------------
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive) is
begin
Console.Sizes (Field) := Length;
if Console.Field_Count >= 1 then
Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count))
+ Console.Sizes (Console.Fields (Console.Field_Count));
else
Console.Cols (Field) := 1;
end if;
Console.Field_Count := Console.Field_Count + 1;
Console.Fields (Console.Field_Count) := Field;
Console_Type'Class (Console).Print_Title (Field, Title);
end Print_Title;
-- ------------------------------
-- Format the address and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr) is
Value : constant String := MAT.Types.Hex_Image (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the size and print it for the given field.
-- ------------------------------
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size) is
Value : constant String := MAT.Types.Target_Size'Image (Size);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Size;
-- ------------------------------
-- Format the thread information and print it for the given field.
-- ------------------------------
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref) is
Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Thread;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer) is
Val : constant String := Integer'Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val);
end Print_Field;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value));
end Print_Field;
end MAT.Consoles;
|
Implement the Print_Thread procedure
|
Implement the Print_Thread procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
048e6c86f40db2db71f5f60bd1bda24ab3851d29
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with ADO.Objects;
with ADO.SQL;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- 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) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- 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) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- 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) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
Ctx.Start;
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if not Page.Is_Inserted then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
Ctx.Commit;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with ADO.Objects;
with ADO.SQL;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- 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) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- 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) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- 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) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- 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) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
Ctx.Start;
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if not Page.Is_Inserted then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Set_Page_Version (Page.Get_Last_Version);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
Ctx.Commit;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
Set the wiki content page version attribute
|
Set the wiki content page version attribute
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
41dc4d9755c67f5b6c0ca776bf40055494c73af3
|
src/mysql/ado-drivers-connections-mysql.adb
|
src/mysql/ado-drivers-connections-mysql.adb
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Identification;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.Schemas.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement {0}: connection is closed",
Query);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create delete statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create insert statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create update statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Mysql.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
raise Connection_Error with "Database connection is closed";
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
if Database.Server /= null then
Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident);
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Server : Mysql_Access;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Task {0} connecting to {1}:{2}",
Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task),
To_String (Config.Server), To_String (Config.Database));
if Config.Get_Property ("password") = "" then
Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user"));
else
Log.Debug ("MySQL connection with user={0} password=XXXXXXXX",
Config.Get_Property ("user"));
end if;
Connection := mysql_init (null);
Server := mysql_real_connect (Connection, ADO.C.To_C (Host),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.Log_URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
D.Id := D.Id + 1;
declare
Ident : constant String := Util.Strings.Image (D.Id);
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name, Item : in Util.Properties.Value);
procedure Configure (Name, Item : in Util.Properties.Value) is
Value : constant String := To_String (Item);
begin
if Name = "encoding" then
Database.Execute ("SET NAMES " & Value);
Database.Execute ("SET CHARACTER SET " & Value);
Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'");
Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'");
elsif Name /= "user" and Name /= "password" then
Database.Execute ("SET " & To_String (Name) & "='" & Value & "'");
end if;
end Configure;
begin
Database.Ident (1 .. Ident'Length) := Ident;
Database.Server := Server;
Database.Name := Config.Database;
-- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands.
-- Typical configuration includes:
-- encoding=utf8
-- collation_connection=utf8_general_ci
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Identification;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.Schemas.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement {0}: connection is closed",
Query);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create delete statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create insert statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create update statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Mysql.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
raise Connection_Error with "Database connection is closed";
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
if Database.Server /= null then
Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident);
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Server : Mysql_Access;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Task {0} connecting to {1}:{2}",
Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task),
To_String (Config.Server), To_String (Config.Database));
if Config.Get_Property ("password") = "" then
Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user"));
else
Log.Debug ("MySQL connection with user={0} password=XXXXXXXX",
Config.Get_Property ("user"));
end if;
Connection := mysql_init (null);
Server := mysql_real_connect (Connection, ADO.C.To_C (Host),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.Log_URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
D.Id := D.Id + 1;
declare
Ident : constant String := Util.Strings.Image (D.Id);
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
Value : constant String := Util.Properties.To_String (Item);
begin
if Name = "encoding" then
Database.Execute ("SET NAMES " & Value);
Database.Execute ("SET CHARACTER SET " & Value);
Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'");
Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'");
elsif Name /= "user" and Name /= "password" then
Database.Execute ("SET " & Name & "='" & Value & "'");
end if;
end Configure;
begin
Database.Ident (1 .. Ident'Length) := Ident;
Database.Server := Server;
Database.Name := Config.Database;
-- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands.
-- Typical configuration includes:
-- encoding=utf8
-- collation_connection=utf8_general_ci
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
Update to use the new Iterate procedure from Util.Properties package
|
Update to use the new Iterate procedure from Util.Properties package
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
8bdd02e52284fadf72117d1ac5a0ccdccbbadf97
|
examples/common/initialize.adb
|
examples/common/initialize.adb
|
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with GL.Errors;
with Glfw;
with Glfw.Input.Mouse;
with Glfw.Windows;
with Glfw.Windows.Context;
with Glfw.Windows.Hints;
with Utilities;
procedure Initialize (Main_Window : in out Glfw.Windows.Window;
Window_Title : String) is
procedure Enable_Callbacks is
begin
Main_Window.Enable_Callback (Glfw.Windows.Callbacks.Size);
Main_Window.Enable_Callback (Glfw.Windows.Callbacks.Key);
end Enable_Callbacks;
-- ------------------------------------------------------------------------
procedure Set_Window_Hints is
Min_Major_Version : constant Integer := 3;
Minor_Version : constant Integer := 2;
begin
Glfw.Windows.Hints.Set_Minimum_OpenGL_Version
(Min_Major_Version, Minor_Version);
Glfw.Windows.Hints.Set_Forward_Compat (True);
Glfw.Windows.Hints.Set_Profile (Glfw.Windows.Context.Core_Profile);
Glfw.Windows.Hints.Set_Debug_Context (True);
-- Set samples to 16 before taking screen shots.
Glfw.Windows.Hints.Set_Samples (4);
end Set_Window_Hints;
-- ------------------------------------------------------------------------
Window_Width : constant Glfw.Size := 800;
Window_Height : constant Glfw.Size := 600;
Cursor : Glfw.Input.Mouse.Cursor_Mode := Glfw.Input.Mouse.Hidden;
begin
Set_Window_Hints;
Main_Window.Init (Window_Width, Window_Height, Window_Title);
Glfw.Windows.Context.Make_Current (Main_Window'Access);
Enable_Callbacks;
Main_Window.Set_Cursor_Mode (Cursor);
Utilities.Show_GL_Data;
exception
when others =>
Put_Line ("An exceptiom occurred in Initialize.");
raise;
end Initialize;
|
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Glfw;
with Glfw.Input.Mouse;
with Glfw.Windows;
with Glfw.Windows.Context;
with Glfw.Windows.Hints;
with Utilities;
procedure Initialize (Main_Window : in out Glfw.Windows.Window;
Window_Title : String) is
procedure Enable_Callbacks is
begin
Main_Window.Enable_Callback (Glfw.Windows.Callbacks.Size);
Main_Window.Enable_Callback (Glfw.Windows.Callbacks.Key);
end Enable_Callbacks;
-- ------------------------------------------------------------------------
procedure Set_Window_Hints is
Min_Major_Version : constant Integer := 3;
Minor_Version : constant Integer := 2;
begin
Glfw.Windows.Hints.Set_Minimum_OpenGL_Version
(Min_Major_Version, Minor_Version);
Glfw.Windows.Hints.Set_Forward_Compat (True);
Glfw.Windows.Hints.Set_Profile (Glfw.Windows.Context.Core_Profile);
Glfw.Windows.Hints.Set_Debug_Context (True);
-- Set samples to 16 before taking screen shots.
Glfw.Windows.Hints.Set_Samples (4);
end Set_Window_Hints;
-- ------------------------------------------------------------------------
Window_Width : constant Glfw.Size := 800;
Window_Height : constant Glfw.Size := 600;
Cursor : Glfw.Input.Mouse.Cursor_Mode := Glfw.Input.Mouse.Hidden;
begin
Set_Window_Hints;
Main_Window.Init (Window_Width, Window_Height, Window_Title);
Glfw.Windows.Context.Make_Current (Main_Window'Access);
Enable_Callbacks;
Main_Window.Set_Cursor_Mode (Cursor);
Utilities.Show_GL_Data;
exception
when others =>
Put_Line ("An exception occurred in Initialize.");
raise;
end Initialize;
|
Remove unneeded with.
|
Remove unneeded with.
|
Ada
|
mit
|
rogermc2/OpenGLAda
|
56bfcaf89ea39c1c5a3a852e8ee7df822131edbf
|
src/gl/implementation/gl-objects-programs-uniforms.adb
|
src/gl/implementation/gl-objects-programs-uniforms.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 GL.API.Uniforms.Singles;
with GL.API.Uniforms.Doubles;
with GL.API.Uniforms.Ints;
with GL.API.Uniforms.UInts;
with GL.Low_Level;
package body GL.Objects.Programs.Uniforms is
function Create_Uniform (Object : Program; Location : Int) return Uniform is
begin
return Uniform'(Program => Object, Location => Location);
end Create_Uniform;
-----------------------------------------------------------------------------
-- Singles --
-----------------------------------------------------------------------------
procedure Set_Single (Location : Uniform; Value : Single) is
begin
API.Uniforms.Singles.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Single;
procedure Set_Singles (Location : Uniform; V1, V2 : Single) is
begin
API.Uniforms.Singles.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector2) is
begin
API.Uniforms.Singles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 2, (1 => Value));
end Set_Single_Vector;
procedure Set_Singles (Location : Uniform; V1, V2, V3 : Single) is
begin
API.Uniforms.Singles.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector3) is
begin
API.Uniforms.Singles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 3, (1 => Value));
end Set_Single_Vector;
procedure Set_Singles (Location : Uniform; V1, V2, V3, V4 : Single) is
begin
API.Uniforms.Singles.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector4) is
begin
API.Uniforms.Singles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 4, (1 => Value));
end Set_Single_Vector;
procedure Set_Single_Array (Location : Uniform; Value : Single_Array) is
begin
API.Uniforms.Singles.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Array;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector2_Array) is
begin
API.Uniforms.Singles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector3_Array) is
begin
API.Uniforms.Singles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector4_Array) is
begin
API.Uniforms.Singles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix2) is
begin
API.Uniforms.Singles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix3) is
begin
API.Uniforms.Singles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix4) is
begin
API.Uniforms.Singles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix2_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix3_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix4_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
-----------------------------------------------------------------------------
-- Doubles --
-----------------------------------------------------------------------------
procedure Set_Double (Location : Uniform; Value : Double) is
begin
API.Uniforms.Doubles.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Double;
procedure Set_Doubles (Location : Uniform; V1, V2 : Double) is
begin
API.Uniforms.Doubles.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector2) is
begin
API.Uniforms.Doubles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 2, (1 => Value));
end Set_Double_Vector;
procedure Set_Doubles (Location : Uniform; V1, V2, V3 : Double) is
begin
API.Uniforms.Doubles.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector3) is
begin
API.Uniforms.Doubles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 3, (1 => Value));
end Set_Double_Vector;
procedure Set_Doubles (Location : Uniform; V1, V2, V3, V4 : Double) is
begin
API.Uniforms.Doubles.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector4) is
begin
API.Uniforms.Doubles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 4, (1 => Value));
end Set_Double_Vector;
procedure Set_Double_Array (Location : Uniform; Value : Double_Array) is
begin
API.Uniforms.Doubles.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Array;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector2_Array) is
begin
API.Uniforms.Doubles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector3_Array) is
begin
API.Uniforms.Doubles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector4_Array) is
begin
API.Uniforms.Doubles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix2) is
begin
API.Uniforms.Doubles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix3) is
begin
API.Uniforms.Doubles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix4) is
begin
API.Uniforms.Doubles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix2_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix3_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix4_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
-----------------------------------------------------------------------------
-- Integers --
-----------------------------------------------------------------------------
procedure Set_Int (Location : Uniform; Value : Int) is
begin
API.Uniforms.Ints.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Int;
procedure Set_Ints (Location : Uniform; V1, V2 : Int) is
begin
API.Uniforms.Ints.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector2) is
begin
API.Uniforms.Ints.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 2, (1 => Value));
end Set_Int_Vector;
procedure Set_Ints (Location : Uniform; V1, V2, V3 : Int) is
begin
API.Uniforms.Ints.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector3) is
begin
API.Uniforms.Ints.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 3, (1 => Value));
end Set_Int_Vector;
procedure Set_Ints (Location : Uniform; V1, V2, V3, V4 : Int) is
begin
API.Uniforms.Ints.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector4) is
begin
API.Uniforms.Ints.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 4, (1 => Value));
end Set_Int_Vector;
procedure Set_Int_Array (Location : Uniform; Value : Int_Array) is
begin
API.Uniforms.Ints.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Int_Array;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector2_Array) is
begin
API.Uniforms.Ints.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 2, Value);
end Set_Int_Vectors;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector3_Array) is
begin
API.Uniforms.Ints.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 3, Value);
end Set_Int_Vectors;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector4_Array) is
begin
API.Uniforms.Ints.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 4, Value);
end Set_Int_Vectors;
-----------------------------------------------------------------------------
-- Unsigned Integers --
-----------------------------------------------------------------------------
procedure Set_UInt (Location : Uniform; Value : UInt) is
begin
API.Uniforms.UInts.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_UInt;
procedure Set_UInts (Location : Uniform; V1, V2 : UInt) is
begin
API.Uniforms.UInts.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector2) is
begin
API.Uniforms.UInts.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 2, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInts (Location : Uniform; V1, V2, V3 : UInt) is
begin
API.Uniforms.UInts.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector3) is
begin
API.Uniforms.UInts.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 3, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInts (Location : Uniform; V1, V2, V3, V4 : UInt) is
begin
API.Uniforms.UInts.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector4) is
begin
API.Uniforms.UInts.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 4, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInt_Array (Location : Uniform; Value : UInt_Array) is
begin
API.Uniforms.UInts.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Array;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector2_Array) is
begin
API.Uniforms.UInts.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector3_Array) is
begin
API.Uniforms.UInts.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector4_Array) is
begin
API.Uniforms.UInts.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
end GL.Objects.Programs.Uniforms;
|
-- 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 GL.API.Uniforms.Singles;
with GL.API.Uniforms.Doubles;
with GL.API.Uniforms.Ints;
with GL.API.Uniforms.UInts;
with GL.Low_Level;
package body GL.Objects.Programs.Uniforms is
function Create_Uniform (Object : Program; Location : Int) return Uniform is
begin
return Uniform'(Program => Object, Location => Location);
end Create_Uniform;
-----------------------------------------------------------------------------
-- Singles --
-----------------------------------------------------------------------------
procedure Set_Single (Location : Uniform; Value : Single) is
begin
API.Uniforms.Singles.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Single;
procedure Set_Singles (Location : Uniform; V1, V2 : Single) is
begin
API.Uniforms.Singles.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector2) is
begin
API.Uniforms.Singles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Single_Vector;
procedure Set_Singles (Location : Uniform; V1, V2, V3 : Single) is
begin
API.Uniforms.Singles.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector3) is
begin
API.Uniforms.Singles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Single_Vector;
procedure Set_Singles (Location : Uniform; V1, V2, V3, V4 : Single) is
begin
API.Uniforms.Singles.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Singles;
procedure Set_Single_Vector (Location : Uniform; Value : Singles.Vector4) is
begin
API.Uniforms.Singles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Single_Vector;
procedure Set_Single_Array (Location : Uniform; Value : Single_Array) is
begin
API.Uniforms.Singles.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Array;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector2_Array) is
begin
API.Uniforms.Singles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector3_Array) is
begin
API.Uniforms.Singles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Vectors (Location : Uniform; Value : Singles.Vector4_Array) is
begin
API.Uniforms.Singles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Single_Vectors;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix2) is
begin
API.Uniforms.Singles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix3) is
begin
API.Uniforms.Singles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrix (Location : Uniform; Value : Singles.Matrix4) is
begin
API.Uniforms.Singles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Single_Matrix;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix2_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix3_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
procedure Set_Single_Matrices (Location : Uniform; Value : Singles.Matrix4_Array) is
begin
API.Uniforms.Singles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Single_Matrices;
-----------------------------------------------------------------------------
-- Doubles --
-----------------------------------------------------------------------------
procedure Set_Double (Location : Uniform; Value : Double) is
begin
API.Uniforms.Doubles.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Double;
procedure Set_Doubles (Location : Uniform; V1, V2 : Double) is
begin
API.Uniforms.Doubles.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector2) is
begin
API.Uniforms.Doubles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Double_Vector;
procedure Set_Doubles (Location : Uniform; V1, V2, V3 : Double) is
begin
API.Uniforms.Doubles.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector3) is
begin
API.Uniforms.Doubles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Double_Vector;
procedure Set_Doubles (Location : Uniform; V1, V2, V3, V4 : Double) is
begin
API.Uniforms.Doubles.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Doubles;
procedure Set_Double_Vector (Location : Uniform; Value : Doubles.Vector4) is
begin
API.Uniforms.Doubles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Double_Vector;
procedure Set_Double_Array (Location : Uniform; Value : Double_Array) is
begin
API.Uniforms.Doubles.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Array;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector2_Array) is
begin
API.Uniforms.Doubles.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector3_Array) is
begin
API.Uniforms.Doubles.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Vectors (Location : Uniform; Value : Doubles.Vector4_Array) is
begin
API.Uniforms.Doubles.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Double_Vectors;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix2) is
begin
API.Uniforms.Doubles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix3) is
begin
API.Uniforms.Doubles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrix (Location : Uniform; Value : Doubles.Matrix4) is
begin
API.Uniforms.Doubles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
1, Low_Level.False, (1 => Value));
end Set_Double_Matrix;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix2_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix2 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix3_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix3 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
procedure Set_Double_Matrices (Location : Uniform; Value : Doubles.Matrix4_Array) is
begin
API.Uniforms.Doubles.Uniform_Matrix4 (Location.Program.Reference.GL_Id,
Location.Location,
Value'Length, Low_Level.False, Value);
end Set_Double_Matrices;
-----------------------------------------------------------------------------
-- Integers --
-----------------------------------------------------------------------------
procedure Set_Int (Location : Uniform; Value : Int) is
begin
API.Uniforms.Ints.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_Int;
procedure Set_Ints (Location : Uniform; V1, V2 : Int) is
begin
API.Uniforms.Ints.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector2) is
begin
API.Uniforms.Ints.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Int_Vector;
procedure Set_Ints (Location : Uniform; V1, V2, V3 : Int) is
begin
API.Uniforms.Ints.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector3) is
begin
API.Uniforms.Ints.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Int_Vector;
procedure Set_Ints (Location : Uniform; V1, V2, V3, V4 : Int) is
begin
API.Uniforms.Ints.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_Ints;
procedure Set_Int_Vector (Location : Uniform; Value : Ints.Vector4) is
begin
API.Uniforms.Ints.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_Int_Vector;
procedure Set_Int_Array (Location : Uniform; Value : Int_Array) is
begin
API.Uniforms.Ints.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_Int_Array;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector2_Array) is
begin
API.Uniforms.Ints.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 2, Value);
end Set_Int_Vectors;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector3_Array) is
begin
API.Uniforms.Ints.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 3, Value);
end Set_Int_Vectors;
procedure Set_Int_Vectors (Location : Uniform; Value : Ints.Vector4_Array) is
begin
API.Uniforms.Ints.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length * 4, Value);
end Set_Int_Vectors;
-----------------------------------------------------------------------------
-- Unsigned Integers --
-----------------------------------------------------------------------------
procedure Set_UInt (Location : Uniform; Value : UInt) is
begin
API.Uniforms.UInts.Uniform1 (Location.Program.Reference.GL_Id,
Location.Location, Value);
end Set_UInt;
procedure Set_UInts (Location : Uniform; V1, V2 : UInt) is
begin
API.Uniforms.UInts.Uniform2 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector2) is
begin
API.Uniforms.UInts.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInts (Location : Uniform; V1, V2, V3 : UInt) is
begin
API.Uniforms.UInts.Uniform3 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector3) is
begin
API.Uniforms.UInts.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInts (Location : Uniform; V1, V2, V3, V4 : UInt) is
begin
API.Uniforms.UInts.Uniform4 (Location.Program.Reference.GL_Id,
Location.Location, V1, V2, V3, V4);
end Set_UInts;
procedure Set_UInt_Vector (Location : Uniform; Value : UInts.Vector4) is
begin
API.Uniforms.UInts.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, 1, (1 => Value));
end Set_UInt_Vector;
procedure Set_UInt_Array (Location : Uniform; Value : UInt_Array) is
begin
API.Uniforms.UInts.Uniform1v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Array;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector2_Array) is
begin
API.Uniforms.UInts.Uniform2v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector3_Array) is
begin
API.Uniforms.UInts.Uniform3v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
procedure Set_UInt_Vectors (Location : Uniform; Value : UInts.Vector4_Array) is
begin
API.Uniforms.UInts.Uniform4v (Location.Program.Reference.GL_Id,
Location.Location, Value'Length, Value);
end Set_UInt_Vectors;
end GL.Objects.Programs.Uniforms;
|
Fix setters of vector uniforms
|
gl: Fix setters of vector uniforms
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
aa57bd5366a203f448d450ffbf0d0f2da6e869ef
|
awa/src/awa-components-wikis.ads
|
awa/src/awa-components-wikis.ads
|
-----------------------------------------------------------------------
-- 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;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- 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;
-- 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;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in 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;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ASF.Contexts.Faces;
with ASF.Components;
with ASF.Components.Html;
with Wiki.Strings;
with Wiki.Render;
with Wiki.Render.Links;
package AWA.Components.Wikis is
use ASF.Contexts.Faces;
-- The wiki format of the wiki text. The valid values are:
-- dotclear, google, creole, phpbb, mediawiki
FORMAT_NAME : constant String := "format";
VALUE_NAME : constant String := ASF.Components.VALUE_NAME;
-- The link renderer bean that controls the generation of page and image links.
LINKS_NAME : constant String := "links";
-- ------------------------------
-- Wiki component
-- ------------------------------
--
-- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/>
--
type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record;
type UIWiki_Access is access all UIWiki'Class;
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax;
-- Get the links renderer that must be used to render image and page links.
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access;
-- Render the wiki text
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class);
use Ada.Strings.Wide_Wide_Unbounded;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Links.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- Make a link adding a prefix unless the link is already absolute.
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
private
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean;
end AWA.Components.Wikis;
|
Update to use the new Wiki.Render.Links package and interfaces
|
Update to use the new Wiki.Render.Links package and interfaces
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6aabbe96e26e8d7beed148c753dd22417c23ab68
|
testcases/bad_select/bad_select.adb
|
testcases/bad_select/bad_select.adb
|
with AdaBase;
with Connect;
with CommonText;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Bad_Select is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
package CT renames CommonText;
row : ARS.DataRow_Access;
sql : String := "SELECT fruit, calories FROM froits " &
"WHERE color = 'red'";
begin
declare
begin
CON.connect_database;
exception
when others =>
TIO.Put_Line ("database connect failed.");
return;
end;
CON.STMT := CON.DR.query (sql);
TIO.Put_Line ("Query successful: " & CON.STMT.successful'Img);
if not CON.STMT.successful then
TIO.Put_Line (" Driver message: " & CON.STMT.last_driver_message);
TIO.Put_Line (" Driver code: " & CON.STMT.last_driver_code'Img);
TIO.Put_Line (" SQL State: " & CON.STMT.last_sql_state);
-- Fix SQL typo
sql (31) := 'u';
TIO.Put_Line ("");
TIO.Put_Line ("SQL now: " & sql);
CON.STMT := CON.DR.query (sql);
TIO.Put_Line ("Query successful: " & CON.STMT.successful'Img);
if CON.STMT.fetch_next (row) then
TIO.Put_Line (" Number fields:" & row.count'Img);
CON.STMT.discard_rest;
TIO.Put_Line (" Data discarded: " & CON.STMT.data_discarded'Img);
end if;
end if;
CON.DR.disconnect;
end Bad_Select;
|
with AdaBase;
with Connect;
with CommonText;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Bad_Select is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
package CT renames CommonText;
row : ARS.DataRow;
sql : String := "SELECT fruit, calories FROM froits " &
"WHERE color = 'red'";
begin
begin
CON.connect_database;
exception
when others =>
TIO.Put_Line ("database connect failed.");
return;
end;
declare
stmt : CON.Stmt_Type := CON.DR.query (sql);
begin
TIO.Put_Line ("Query successful: " & stmt.successful'Img);
if not stmt.successful then
TIO.Put_Line (" Driver message: " & stmt.last_driver_message);
TIO.Put_Line (" Driver code: " & stmt.last_driver_code'Img);
TIO.Put_Line (" SQL State: " & stmt.last_sql_state);
-- Fix SQL typo
sql (31) := 'u';
TIO.Put_Line ("");
TIO.Put_Line ("SQL now: " & sql);
stmt := CON.DR.query (sql);
TIO.Put_Line ("Query successful: " & stmt.successful'Img);
row := stmt.fetch_next;
if not row.data_exhausted then
TIO.Put_Line (" Number fields:" & row.count'Img);
stmt.discard_rest;
TIO.Put_Line (" Data discarded: " & stmt.data_discarded'Img);
end if;
end if;
end;
CON.DR.disconnect;
end Bad_Select;
|
fix bad_select test case
|
fix bad_select test case
|
Ada
|
isc
|
jrmarino/AdaBase
|
308cd826803eb40ff41a77278462dae292157c9e
|
orka_simd/src/x86/gnat/orka-simd-sse2-integers-logical.adb
|
orka_simd/src/x86/gnat/orka-simd-sse2-integers-logical.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Unchecked_Conversion;
package body Orka.SIMD.SSE2.Integers.Logical is
type Unsigned_128 is array (Index_2D) of Unsigned_64
with Alignment => 16;
pragma Machine_Attribute (Unsigned_128, "vector_type");
function And_Not (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pandn128";
function "and" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pand128";
function "or" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pand128";
function "xor" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pand128";
----------------------------------------------------------------------------
function Convert is new Ada.Unchecked_Conversion (m128i, Unsigned_128);
function Convert is new Ada.Unchecked_Conversion (Unsigned_128, m128i);
function And_Not (Left, Right : m128i) return m128i is
(Convert (And_Not (Convert (Left), Convert (Right))));
function "and" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) and Convert (Right)));
function "or" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) or Convert (Right)));
function "xor" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) xor Convert (Right)));
end Orka.SIMD.SSE2.Integers.Logical;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Unchecked_Conversion;
package body Orka.SIMD.SSE2.Integers.Logical is
type Unsigned_128 is array (Index_2D) of Unsigned_64
with Alignment => 16;
pragma Machine_Attribute (Unsigned_128, "vector_type");
function And_Not (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pandn128";
function "and" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pand128";
function "or" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_por128";
function "xor" (Left, Right : Unsigned_128) return Unsigned_128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_pxor128";
----------------------------------------------------------------------------
function Convert is new Ada.Unchecked_Conversion (m128i, Unsigned_128);
function Convert is new Ada.Unchecked_Conversion (Unsigned_128, m128i);
function And_Not (Left, Right : m128i) return m128i is
(Convert (And_Not (Convert (Left), Convert (Right))));
function "and" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) and Convert (Right)));
function "or" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) or Convert (Right)));
function "xor" (Left, Right : m128i) return m128i is
(Convert (Convert (Left) xor Convert (Right)));
end Orka.SIMD.SSE2.Integers.Logical;
|
Fix import correct SSE2 intrinsic for operators 'or' and 'xor'
|
simd: Fix import correct SSE2 intrinsic for operators 'or' and 'xor'
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
4b8df4d2809cd8e6faaf04b3d0a7724a50ab0f4d
|
src/sys/streams/util-streams-sockets.adb
|
src/sys/streams/util-streams-sockets.adb
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Sockets is
-- -----------------------
-- Initialize the socket stream.
-- -----------------------
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Stream.Sock /= GNAT.Sockets.No_Socket then
raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened";
end if;
Stream.Sock := Socket;
end Open;
-- -----------------------
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
-- -----------------------
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Stream.Sock /= GNAT.Sockets.No_Socket then
raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened";
end if;
GNAT.Sockets.Create_Socket (Socket => Stream.Sock,
Family => Server.Family);
GNAT.Sockets.Connect_Socket (Socket => Stream.Sock,
Server => Server);
end Connect;
-- -----------------------
-- Close the socket stream.
-- -----------------------
overriding
procedure Close (Stream : in out Socket_Stream) is
begin
GNAT.Sockets.Close_Socket (Stream.Sock);
Stream.Sock := GNAT.Sockets.No_Socket;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Last : Ada.Streams.Stream_Element_Offset;
pragma Unreferenced (Last);
begin
GNAT.Sockets.Send_Socket (Stream.Sock, Buffer, Last);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
GNAT.Sockets.Receive_Socket (Stream.Sock, Into, Last);
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Socket_Stream) is
use type GNAT.Sockets.Socket_Type;
begin
if Object.Sock /= GNAT.Sockets.No_Socket then
Object.Close;
end if;
end Finalize;
end Util.Streams.Sockets;
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Sockets is
-- -----------------------
-- Initialize the socket stream.
-- -----------------------
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Stream.Sock /= GNAT.Sockets.No_Socket then
raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened";
end if;
Stream.Sock := Socket;
end Open;
-- -----------------------
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
-- -----------------------
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Stream.Sock /= GNAT.Sockets.No_Socket then
raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened";
end if;
GNAT.Sockets.Create_Socket (Socket => Stream.Sock,
Family => Server.Family);
GNAT.Sockets.Connect_Socket (Socket => Stream.Sock,
Server => Server);
end Connect;
-- -----------------------
-- Close the socket stream.
-- -----------------------
overriding
procedure Close (Stream : in out Socket_Stream) is
begin
GNAT.Sockets.Close_Socket (Stream.Sock);
Stream.Sock := GNAT.Sockets.No_Socket;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Unused_Last : Ada.Streams.Stream_Element_Offset;
begin
GNAT.Sockets.Send_Socket (Stream.Sock, Buffer, Unused_Last);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
GNAT.Sockets.Receive_Socket (Stream.Sock, Into, Last);
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Socket_Stream) is
use type GNAT.Sockets.Socket_Type;
begin
if Object.Sock /= GNAT.Sockets.No_Socket then
Object.Close;
end if;
end Finalize;
end Util.Streams.Sockets;
|
Fix for GCC 12
|
Fix for GCC 12
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e4235e937bacce6b9926307cde9226a91cdcb529
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 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 Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Info ("A {0} {1} {2} {3}", "info", "message", "not", "printed");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Log;
procedure Test_Debug (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
C : Ada.Strings.Unbounded.Unbounded_String;
begin
L.Set_Level (DEBUG_LEVEL);
L.Info ("My log message");
L.Error ("My error message");
L.Debug ("A {0} {1} {2} {3}", "debug", "message", "not", "printed");
L.Debug ("A {0} {1} {2} {3}", C, "message", "printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Debug;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test_perf.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log");
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", Path);
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.appender.test.log.File",
Util.Tests.Get_Test_Path ("test-default.log"));
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log");
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Append_Path : constant String := Util.Tests.Get_Test_Path ("test-append.log");
Append2_Path : constant String := Util.Tests.Get_Test_Path ("test-append2.log");
Global_Path : constant String := Util.Tests.Get_Test_Path ("test-append-global.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Append_Path);
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", Global_Path);
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", Append2_Path);
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size (Append_Path) > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size (Append2_Path) > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size (Global_Path) > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test_err.log");
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path);
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
L : constant Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
procedure Test_Log_Traceback (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-traceback.log");
Props : Util.Properties.Manager;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.appender.test.append", "false");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.rootCategory", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Error ("This is the error test message");
raise Constraint_Error with "Test";
exception
when E : others =>
L.Error ("Something wrong", E, True);
end;
Props.Set ("log4j.rootCategory", "DEBUG,console");
Props.Set ("log4j.appender.console", "Console");
Util.Log.Loggers.Initialize (Props);
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content,
"Invalid console log (ERROR)");
end Test_Log_Traceback;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Debug'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error",
Test_Log_Traceback'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 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 Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Info ("A {0} {1} {2} {3}", "info", "message", "not", "printed");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Log;
procedure Test_Debug (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
C : Ada.Strings.Unbounded.Unbounded_String;
begin
L.Set_Level (DEBUG_LEVEL);
L.Info ("My log message");
L.Error ("My error message");
L.Debug ("A {0} {1} {2} {3}", "debug", "message", "not", "printed");
L.Debug ("A {0} {1} {2} {3}", C, "message", "printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Debug;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test_perf.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log");
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", Path);
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.appender.test.log.File",
Util.Tests.Get_Test_Path ("test-default.log"));
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log");
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Append_Path : constant String := Util.Tests.Get_Test_Path ("test-append.log");
Append2_Path : constant String := Util.Tests.Get_Test_Path ("test-append2.log");
Global_Path : constant String := Util.Tests.Get_Test_Path ("test-append-global.log");
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Append_Path);
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", Global_Path);
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", Append2_Path);
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size (Append_Path) > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size (Append2_Path) > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size (Global_Path) > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test_err.log");
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path);
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
pragma Unreferenced (T);
L : constant Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
procedure Test_Log_Traceback (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-traceback.log");
Props : Util.Properties.Manager;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", Path);
Props.Set ("log4j.appender.test.append", "false");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.rootCategory", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Error ("This is the error test message");
raise Constraint_Error with "Test";
exception
when E : others =>
L.Error ("Something wrong", E, True);
end;
Props.Set ("log4j.rootCategory", "DEBUG,console");
Props.Set ("log4j.appender.console", "Console");
Util.Log.Loggers.Initialize (Props);
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content,
"Invalid console log (ERROR)");
end Test_Log_Traceback;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Debug'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error",
Test_Log_Traceback'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e4450cf41d2318c45fcc154ee03ca405a228b01c
|
src/ado-parameters.ads
|
src/ado-parameters.ads
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
Update the Expander documentation
|
Update the Expander documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
8c6cd3af7c93f6d9a9f336376198cb8b59325bbb
|
src/base/beans/util-beans-objects-datasets.adb
|
src/base/beans/util-beans-objects-datasets.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Length then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := Into.Count + (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
end Util.Beans.Objects.Datasets;
|
-----------------------------------------------------------------------
-- util-beans-objects-datasets -- Datasets
-- Copyright (C) 2013, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get an iterator to iterate starting with the first element.
-- ------------------------------
overriding
function First (From : in Dataset) return Iterators.Proxy_Iterator_Access is
Iter : constant Dataset_Iterator_Access := new Dataset_Iterator;
begin
Iter.Current_Pos := 1;
Iter.Current.Map := From.Current.Map;
if From.Count > 0 then
Iter.Current.Data := From.Data (1);
end if;
return Iter.all'Access;
end First;
-- ------------------------------
-- Get an iterator to iterate starting with the last element.
-- ------------------------------
overriding
function Last (From : in Dataset) return Iterators.Proxy_Iterator_Access is
Iter : constant Dataset_Iterator_Access := new Dataset_Iterator;
begin
Iter.Current_Pos := From.Count;
Iter.Current.Map := From.Current.Map;
if From.Count > 0 then
Iter.Current.Data := From.Data (From.Count);
end if;
return Iter.all'Access;
end Last;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Length then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := Into.Count + (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Get an iterator to iterate starting with the first element.
-- ------------------------------
overriding
function First (From : in Row) return Iterators.Proxy_Iterator_Access is
Iter : constant Row_Iterator_Access := new Row_Iterator;
begin
Iter.Pos := From.Map.First;
Iter.Data := From.Data;
return Iter.all'Access;
end First;
-- ------------------------------
-- Get an iterator to iterate starting with the last element.
-- ------------------------------
overriding
function Last (From : in Row) return Iterators.Proxy_Iterator_Access is
begin
return null;
end Last;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Iter : in out Dataset_Iterator) is
begin
Iter.Row := To_Object (Value => Iter.Current'Unchecked_Access,
Storage => STATIC);
end Initialize;
function Get_Dataset is
new Util.Beans.Objects.Iterators.Get_Bean (Dataset, Dataset_Access);
overriding
function Has_Element (Iter : in Dataset_Iterator) return Boolean is
List : constant Dataset_Access := Get_Dataset (Iter);
begin
return List /= null and then Iter.Current_Pos /= 0
and then Iter.Current_Pos <= List.Count;
end Has_Element;
overriding
procedure Next (Iter : in out Dataset_Iterator) is
List : constant Dataset_Access := Get_Dataset (Iter);
begin
if List /= null and then Iter.Current_Pos <= List.Count then
Iter.Current_Pos := Iter.Current_Pos + 1;
if Iter.Current_Pos <= List.Count then
Iter.Current.Data := List.Data (Iter.Current_Pos);
end if;
end if;
end Next;
overriding
procedure Previous (Iter : in out Dataset_Iterator) is
List : constant Dataset_Access := Get_Dataset (Iter);
begin
if List /= null and then Iter.Current_Pos > 0 then
Iter.Current_Pos := Iter.Current_Pos - 1;
if Iter.Current_Pos > 0 then
Iter.Current.Data := List.Data (Iter.Current_Pos);
end if;
end if;
end Previous;
overriding
function Element (Iter : in Dataset_Iterator) return Object is
begin
return Iter.Row;
end Element;
overriding
procedure Initialize (Iter : in out Row_Iterator) is
begin
null;
end Initialize;
overriding
function Has_Element (Iter : in Row_Iterator) return Boolean is
begin
return Dataset_Map.Has_Element (Iter.Pos);
end Has_Element;
overriding
procedure Next (Iter : in out Row_Iterator) is
begin
Dataset_Map.Next (Iter.Pos);
end Next;
overriding
procedure Previous (Iter : in out Row_Iterator) is
begin
null;
end Previous;
overriding
function Element (Iter : in Row_Iterator) return Object is
begin
return Iter.Data (Dataset_Map.Element (Iter.Pos));
end Element;
overriding
function Key (Iter : in Row_Iterator) return String is
begin
return Dataset_Map.Key (Iter.Pos);
end Key;
end Util.Beans.Objects.Datasets;
|
Implement the operations for the dataset iterators
|
Implement the operations for the dataset iterators
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c949a6ae49cb9dcfc17217d0666ae57a3792fd1c
|
src/sys/encoders/util-encoders-hmac-sha1.adb
|
src/sys/encoders/util-encoders-hmac-sha1.adb
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base16;
with Util.Encoders.Base64;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package body Util.Encoders.HMAC.SHA1 is
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array is
Ctx : Context;
Result : Util.Encoders.SHA1.Hash_Array;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
-- ------------------------------
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA1.Hash_Array) is
Ctx : Context;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Base64_Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish_Base64 (Ctx, Result, URL);
return Result;
end Sign_Base64;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in String) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length);
for Buf'Address use Key'Address;
pragma Import (Ada, Buf);
begin
Set_Key (E, Buf);
end Set_Key;
IPAD : constant Ada.Streams.Stream_Element := 16#36#;
OPAD : constant Ada.Streams.Stream_Element := 16#5c#;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array) is
begin
-- Reduce the key
if Key'Length > 64 then
Util.Encoders.SHA1.Update (E.SHA, Key);
Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19));
E.Key_Len := 19;
else
E.Key_Len := Key'Length - 1;
E.Key (0 .. E.Key_Len) := Key;
end if;
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := IPAD xor E.Key (I);
end loop;
for I in E.Key_Len + 1 .. 63 loop
Block (I) := IPAD;
end loop;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
end Set_Key;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in String) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array) is
begin
Util.Encoders.SHA1.Finish (E.SHA, Hash);
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := OPAD xor E.Key (I);
end loop;
if E.Key_Len < 63 then
for I in E.Key_Len + 1 .. 63 loop
Block (I) := OPAD;
end loop;
end if;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
Util.Encoders.SHA1.Update (E.SHA, Hash);
Util.Encoders.SHA1.Finish (E.SHA, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base16.Encoder;
begin
Finish (E, H);
B.Convert (H, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base64.Encoder;
begin
Finish (E, H);
B.Set_URL_Mode (URL);
B.Convert (H, Hash);
end Finish_Base64;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
begin
null;
end Transform;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context) is
begin
null;
end Initialize;
end Util.Encoders.HMAC.SHA1;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base16;
with Util.Encoders.Base64;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package body Util.Encoders.HMAC.SHA1 is
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array is
Ctx : Context;
Result : Util.Encoders.SHA1.Hash_Array;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
-- ------------------------------
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA1.Hash_Array) is
Ctx : Context;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Base64_Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish_Base64 (Ctx, Result, URL);
return Result;
end Sign_Base64;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in String) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length);
for Buf'Address use Key'Address;
pragma Import (Ada, Buf);
begin
Set_Key (E, Buf);
end Set_Key;
IPAD : constant Ada.Streams.Stream_Element := 16#36#;
OPAD : constant Ada.Streams.Stream_Element := 16#5c#;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array) is
begin
-- Reduce the key
if Key'Length > 64 then
Util.Encoders.SHA1.Update (E.SHA, Key);
Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19));
E.Key_Len := 19;
else
E.Key_Len := Key'Length - 1;
E.Key (0 .. E.Key_Len) := Key;
end if;
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := IPAD xor E.Key (I);
end loop;
for I in E.Key_Len + 1 .. 63 loop
Block (I) := IPAD;
end loop;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
end Set_Key;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in String) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array) is
begin
Util.Encoders.SHA1.Finish (E.SHA, Hash);
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := OPAD xor E.Key (I);
end loop;
if E.Key_Len < 63 then
for I in E.Key_Len + 1 .. 63 loop
Block (I) := OPAD;
end loop;
end if;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
Util.Encoders.SHA1.Update (E.SHA, Hash);
Util.Encoders.SHA1.Finish (E.SHA, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base16.Encoder;
begin
Finish (E, H);
B.Convert (H, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base64.Encoder;
begin
Finish (E, H);
B.Set_URL_Mode (URL);
B.Convert (H, Hash);
end Finish_Base64;
end Util.Encoders.HMAC.SHA1;
|
Remove the Encoder type and its Transform operation because it was not implemented
|
Remove the Encoder type and its Transform operation because it was not implemented
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
6ab529f1ffd880bf79eac0c5478d258b58cc8b75
|
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
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;
|
-----------------------------------------------------------------------
-- 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);
elsif Name = "rowIndex" then
return EL.Objects.To_Object (From.Row);
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 rowIndex property to the list to indicate the current row index number
|
Add a rowIndex property to the list to indicate the current row index number
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
17be7fb5c2723ac14021099766312af16d4e1dec
|
src/asf-components-html.adb
|
src/asf-components-html.adb
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
with Util.Strings;
package body ASF.Components.Html is
use EL.Objects;
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
TABINDEX_ATTR : aliased constant String := "tabindex";
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Writer : in ResponseWriter_Access) is
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
begin
Writer.Write_Attribute ("id", UI.Get_Client_Id);
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
end if;
if not Is_Null (Style) then
Writer.Write_Attribute ("style", Style);
end if;
if not Is_Null (Title) then
Writer.Write_Attribute ("title", Title);
end if;
end Render_Attributes;
-- ------------------------------
-- Render the attributes which are defined on the component and which are
-- in the list specified by <b>names</b>.
-- ------------------------------
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Names : in Util.Strings.String_Set.Set;
Writer : in ResponseWriter_Access) is
procedure Process_Attribute (Name : in String;
Attr : in UIAttribute) is
begin
if Names.Contains (Name'Unrestricted_Access) then
declare
Value : constant Object := Get_Value (Attr, UI);
begin
if Name = "styleClass" then
Writer.Write_Attribute ("class", Value);
else
Writer.Write_Attribute (Name, Value);
end if;
end;
end if;
end Process_Attribute;
procedure Write_Attributes is new Iterate_Attributes (Process_Attribute);
Id : constant Unbounded_String := UI.Get_Client_Id;
begin
if Length (Id) > 0 then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
Write_Attributes (UI);
end Render_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
end Set_Interactive_Attributes;
end ASF.Components.Html;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
package body ASF.Components.Html is
use EL.Objects;
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
TABINDEX_ATTR : aliased constant String := "tabindex";
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Writer : in ResponseWriter_Access) is
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
begin
Writer.Write_Attribute ("id", UI.Get_Client_Id);
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
end if;
if not Is_Null (Style) then
Writer.Write_Attribute ("style", Style);
end if;
if not Is_Null (Title) then
Writer.Write_Attribute ("title", Title);
end if;
end Render_Attributes;
-- ------------------------------
-- Render the attributes which are defined on the component and which are
-- in the list specified by <b>names</b>.
-- ------------------------------
procedure Render_Attributes (UI : in UIHtmlComponent;
Context : in out Faces_Context'Class;
Names : in Util.Strings.String_Set.Set;
Writer : in ResponseWriter_Access) is
procedure Process_Attribute (Name : in String;
Attr : in UIAttribute) is
begin
if Names.Contains (Name'Unrestricted_Access) then
declare
Value : constant Object := Get_Value (Attr, UI);
begin
if Name = "styleClass" then
Writer.Write_Attribute ("class", Value);
else
Writer.Write_Attribute (Name, Value);
end if;
end;
end if;
end Process_Attribute;
procedure Write_Attributes is new Iterate_Attributes (Process_Attribute);
Id : constant Unbounded_String := UI.Get_Client_Id;
begin
if Length (Id) > 0 then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
Write_Attributes (UI);
end Render_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
Names.Insert (ON_BLUR_ATTR'Access);
Names.Insert (ON_MOUSE_UP_ATTR'Access);
Names.Insert (ON_MOUSE_OVER_ATTR'Access);
Names.Insert (ON_MOUSE_OUT_ATTR'Access);
Names.Insert (ON_MOUSE_MOVE_ATTR'Access);
Names.Insert (ON_MOUSE_DOWN_ATTR'Access);
Names.Insert (ON_KEYUP_ATTR'Access);
Names.Insert (ON_KEYDOWN_ATTR'Access);
Names.Insert (ON_FOCUS_ATTR'Access);
Names.Insert (ON_DBLCLICK_ATTR'Access);
Names.Insert (ON_CLICK_ATTR'Access);
end Set_Interactive_Attributes;
end ASF.Components.Html;
|
Update the definition of interative attributes.
|
Update the definition of interative attributes.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b8b719c8d0c1d159422392ed444d153fd3338ae9
|
src/babel-streams-files.adb
|
src/babel-streams-files.adb
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with System.OS_Constants;
with Ada.Streams;
with Ada.Directories;
with Ada.IO_Exceptions;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
use type Util.Systems.Os.File_Type;
use Util.Systems.Os;
use type Interfaces.C.int;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
File : Util.Systems.Os.File_Type;
begin
File := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Mode);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, Mode);
end if;
end if;
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => File);
if File < 0 then
raise Ada.IO_Exceptions.Name_Error with "Cannot create '" & Path & "'";
end if;
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
Stream.File.Seek (0, Util.Systems.Types.SEEK_SET);
Stream.Eof := False;
end Rewind;
end Babel.Streams.Files;
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with System.OS_Constants;
with Ada.Streams;
with Ada.Directories;
with Ada.IO_Exceptions;
with Interfaces.C;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
function Sys_Fadvise (Fd : in Util.Systems.Os.File_Type;
Offset : in Util.Systems.Types.off_t;
Length : in Util.Systems.Types.off_t;
Advice : in Interfaces.C.int) return Interfaces.C.int;
pragma Import (C, Sys_Fadvise, "posix_fadvise");
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
use type Util.Systems.Os.File_Type;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
Res : Interfaces.C.int;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
if Fd >= 0 then
Res := Sys_Fadvise (Fd, 0, 0, 2);
end if;
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
use type Util.Systems.Os.File_Type;
use Util.Systems.Os;
use type Interfaces.C.int;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
File : Util.Systems.Os.File_Type;
begin
File := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Mode);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, Mode);
end if;
end if;
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => File);
if File < 0 then
raise Ada.IO_Exceptions.Name_Error with "Cannot create '" & Path & "'";
end if;
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
Stream.File.Seek (0, Util.Systems.Types.SEEK_SET);
Stream.Eof := False;
end Rewind;
end Babel.Streams.Files;
|
Use fadvise to indicate files are read sequentially
|
Use fadvise to indicate files are read sequentially
|
Ada
|
apache-2.0
|
stcarrez/babel
|
00e35809381ee85ab6ddb0b7a0b15ff038d60fa7
|
src/gen-commands-layout.adb
|
src/gen-commands-layout.adb
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Cmd.Usage (Name, Generator);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- 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 Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Cmd.Usage (Name, Generator);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
1ecaf43f214335caf4185ba4834d664983d62004
|
src/xml/util-serialize-io-xml.ads
|
src/xml/util-serialize-io-xml.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Streams.Texts;
package Util.Serialize.IO.XML is
Parse_Error : exception;
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class);
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean);
-- Set the XHTML reader to ignore empty lines.
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
type Xhtml_Reader is new Sax.Readers.Reader with private;
-- ------------------------------
-- XML Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating an XML output stream.
-- The stream object takes care of the XML escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Write a character on the response stream and escape that character as necessary.
procedure Write_Escape (Stream : in out Output_Stream'Class;
Char : in Wide_Wide_Character);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new XML object.
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current XML object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a XML name/value attribute.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write a XML name/value entity (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Starts a XML array.
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type);
-- Terminates a XML array.
procedure End_Array (Stream : in out Output_Stream);
-- Return the location where the exception was raised.
function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class)
return String;
private
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator);
overriding
procedure Start_Document (Handler : in out Xhtml_Reader);
overriding
procedure End_Document (Handler : in out Xhtml_Reader);
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence);
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class);
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "");
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence);
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader);
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader);
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "");
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence);
type Xhtml_Reader is new Sax.Readers.Reader with record
Stack_Pos : Natural := 0;
Handler : access Parser'Class;
Text : Ada.Strings.Unbounded.Unbounded_String;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
-- The SAX locator to find the current file and line number.
Locator : Sax.Locators.Locator;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
end record;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Streams.Texts;
package Util.Serialize.IO.XML is
Parse_Error : exception;
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class);
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean);
-- Set the XHTML reader to ignore empty lines.
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
type Xhtml_Reader is new Sax.Readers.Reader with private;
-- ------------------------------
-- XML Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating an XML output stream.
-- The stream object takes care of the XML escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a raw character on the stream.
procedure Write (Stream : in out Output_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Output_Stream;
Item : in String);
-- Write a character on the response stream and escape that character as necessary.
procedure Write_Escape (Stream : in out Output_Stream'Class;
Char : in Wide_Wide_Character);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new XML object.
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current XML object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a XML name/value attribute.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write a XML name/value entity (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Starts a XML array.
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type);
-- Terminates a XML array.
procedure End_Array (Stream : in out Output_Stream);
-- Return the location where the exception was raised.
function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class)
return String;
private
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator);
overriding
procedure Start_Document (Handler : in out Xhtml_Reader);
overriding
procedure End_Document (Handler : in out Xhtml_Reader);
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence);
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class);
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "");
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence);
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader);
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader);
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "");
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence);
type Xhtml_Reader is new Sax.Readers.Reader with record
Stack_Pos : Natural := 0;
Handler : access Parser'Class;
Text : Ada.Strings.Unbounded.Unbounded_String;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
-- The SAX locator to find the current file and line number.
Locator : Sax.Locators.Locator;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
end Util.Serialize.IO.XML;
|
Change Output_Stream implementation to avoid inheriting from Print_Stream but instead allow to use a Print_Stream instance as the output stream. Override the Initialize, Flush, Close, Write procedues. Define the Write_Wide procedure so that the Output_Stream type provides almost the same operations as Print_Stream type.
|
Change Output_Stream implementation to avoid inheriting from Print_Stream but instead
allow to use a Print_Stream instance as the output stream. Override the Initialize,
Flush, Close, Write procedues. Define the Write_Wide procedure so that the Output_Stream
type provides almost the same operations as Print_Stream type.
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d6bdda09192969349bbb43690833f58fe964df0b
|
src/asf-applications-views.adb
|
src/asf-applications-views.adb
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with ASF.Contexts.Facelets;
with ASF.Applications.Main;
with ASF.Components.Base;
with ASF.Components.Core;
with ASF.Responses;
package body ASF.Applications.Views is
use ASF.Components;
type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record
Facelets : access ASF.Views.Facelets.Facelet_Factory;
Application : access ASF.Applications.Main.Application'Class;
end record;
-- Include the definition having the given name.
overriding
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access);
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class;
-- ------------------------------
-- Include the definition having the given name.
-- ------------------------------
overriding
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access) is
use ASF.Views;
Path : constant String := Context.Resolve_Path (Source);
Tree : Facelets.Facelet;
begin
Facelets.Find_Facelet (Factory => Context.Facelets.all,
Name => Path,
Context => Context,
Result => Tree);
Facelets.Build_View (View => Tree,
Context => Context,
Root => Parent);
end Include_Facelet;
-- ------------------------------
-- Get the application associated with this facelet context.
-- ------------------------------
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class is
begin
return Context.Application;
end Get_Application;
-- ------------------------------
-- Get the facelet name from the view name.
-- ------------------------------
function Get_Facelet_Name (Handler : in View_Handler;
Name : in String) return String is
use Ada.Strings.Fixed;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then
return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext);
end if;
return Name & To_String (Handler.File_Ext);
end Get_Facelet_Name;
-- ------------------------------
-- Restore the view identified by the given name in the faces context
-- and create the component tree representing that view.
-- ------------------------------
procedure Restore_View (Handler : in out View_Handler;
Name : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : out ASF.Components.Root.UIViewRoot) is
use ASF.Views;
Ctx : Facelet_Context;
Tree : Facelets.Facelet;
View_Name : constant String := Handler.Get_Facelet_Name (Name);
begin
Ctx.Facelets := Handler.Facelets'Unchecked_Access;
Ctx.Application := Context.Get_Application;
Ctx.Set_ELContext (Context.Get_ELContext);
Facelets.Find_Facelet (Factory => Handler.Facelets,
Name => View_Name,
Context => Ctx,
Result => Tree);
if Facelets.Is_Null (Tree) then
Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
Context.Response_Completed;
return;
end if;
-- Build the component tree for this request.
declare
Root : aliased Core.UIComponentBase;
Node : Base.UIComponent_Access;
begin
Facelets.Build_View (View => Tree,
Context => Ctx,
Root => Root'Unchecked_Access);
ASF.Components.Base.Steal_Root_Component (Root, Node);
ASF.Components.Root.Set_Root (View, Node, View_Name);
end;
end Restore_View;
-- ------------------------------
-- Create a new UIViewRoot instance initialized from the context and with
-- the view identifier. If the view is a valid view, create the component tree
-- representing that view.
-- ------------------------------
procedure Create_View (Handler : in out View_Handler;
Name : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : out ASF.Components.Root.UIViewRoot) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos > 0 then
Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View);
else
Handler.Restore_View (Name, Context, View);
end if;
end Create_View;
-- ------------------------------
-- Render the view represented by the component tree. The view is
-- rendered using the context.
-- ------------------------------
procedure Render_View (Handler : in out View_Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : in ASF.Components.Root.UIViewRoot) is
pragma Unreferenced (Handler);
Root : constant access ASF.Components.Base.UIComponent'Class
:= ASF.Components.Root.Get_Root (View);
begin
if Root /= null then
Root.Encode_All (Context);
end if;
end Render_View;
-- ------------------------------
-- Get the URL suitable for encoding and rendering the view specified by the <b>View</b>
-- identifier.
-- ------------------------------
function Get_Action_URL (Handler : in View_Handler;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
View : in String) return String is
use Ada.Strings.Unbounded;
Pos : constant Natural := Util.Strings.Rindex (View, '.');
Context_Path : constant String := Context.Get_Request.Get_Context_Path;
begin
if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then
return Context_Path & View (View'First .. Pos - 1) & To_String (Handler.View_Ext);
end if;
if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then
return Context_Path & View;
end if;
return Context_Path & View;
end Get_Action_URL;
-- ------------------------------
-- Get the URL for redirecting the user to the specified view.
-- ------------------------------
function Get_Redirect_URL (Handler : in View_Handler;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
View : in String) return String is
begin
return Handler.Get_Action_URL (Context, View);
end Get_Redirect_URL;
-- ------------------------------
-- Initialize the view handler.
-- ------------------------------
procedure Initialize (Handler : out View_Handler;
Components : access ASF.Factory.Component_Factory;
Conf : in Config) is
use ASF.Views;
use Ada.Strings.Unbounded;
begin
Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM));
Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM));
Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM));
Facelets.Initialize (Factory => Handler.Facelets,
Components => Components,
Paths => To_String (Handler.Paths),
Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM),
Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM),
Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM));
end Initialize;
-- ------------------------------
-- Closes the view handler
-- ------------------------------
procedure Close (Handler : in out View_Handler) is
use ASF.Views;
begin
Facelets.Clear_Cache (Handler.Facelets);
end Close;
-- ------------------------------
-- Set the extension mapping rule to find the facelet file from
-- the name.
-- ------------------------------
procedure Set_Extension_Mapping (Handler : in out View_Handler;
From : in String;
Into : in String) is
use Ada.Strings.Unbounded;
begin
Handler.View_Ext := To_Unbounded_String (From);
Handler.File_Ext := To_Unbounded_String (Into);
end Set_Extension_Mapping;
end ASF.Applications.Views;
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with ASF.Contexts.Facelets;
with ASF.Applications.Main;
with ASF.Components.Base;
with ASF.Components.Core;
with ASF.Responses;
package body ASF.Applications.Views is
use ASF.Components;
type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record
Facelets : access ASF.Views.Facelets.Facelet_Factory;
Application : access ASF.Applications.Main.Application'Class;
end record;
-- Include the definition having the given name.
overriding
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access);
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class;
-- ------------------------------
-- Include the definition having the given name.
-- ------------------------------
overriding
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access) is
use ASF.Views;
Path : constant String := Context.Resolve_Path (Source);
Tree : Facelets.Facelet;
begin
Facelets.Find_Facelet (Factory => Context.Facelets.all,
Name => Path,
Context => Context,
Result => Tree);
Facelets.Build_View (View => Tree,
Context => Context,
Root => Parent);
end Include_Facelet;
-- ------------------------------
-- Get the application associated with this facelet context.
-- ------------------------------
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class is
begin
return Context.Application;
end Get_Application;
-- ------------------------------
-- Get the facelet name from the view name.
-- ------------------------------
function Get_Facelet_Name (Handler : in View_Handler;
Name : in String) return String is
use Ada.Strings.Fixed;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then
return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext);
end if;
return Name & To_String (Handler.File_Ext);
end Get_Facelet_Name;
-- ------------------------------
-- Restore the view identified by the given name in the faces context
-- and create the component tree representing that view.
-- ------------------------------
procedure Restore_View (Handler : in out View_Handler;
Name : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : out ASF.Components.Root.UIViewRoot) is
use ASF.Views;
Ctx : Facelet_Context;
Tree : Facelets.Facelet;
View_Name : constant String := Handler.Get_Facelet_Name (Name);
begin
Ctx.Facelets := Handler.Facelets'Unchecked_Access;
Ctx.Application := Context.Get_Application;
Ctx.Set_ELContext (Context.Get_ELContext);
Facelets.Find_Facelet (Factory => Handler.Facelets,
Name => View_Name,
Context => Ctx,
Result => Tree);
if Facelets.Is_Null (Tree) then
Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
Context.Response_Completed;
return;
end if;
-- Build the component tree for this request.
declare
Root : aliased Core.UIComponentBase;
Node : Base.UIComponent_Access;
begin
Facelets.Build_View (View => Tree,
Context => Ctx,
Root => Root'Unchecked_Access);
ASF.Components.Base.Steal_Root_Component (Root, Node);
ASF.Components.Root.Set_Root (View, Node, View_Name);
end;
end Restore_View;
-- ------------------------------
-- Create a new UIViewRoot instance initialized from the context and with
-- the view identifier. If the view is a valid view, create the component tree
-- representing that view.
-- ------------------------------
procedure Create_View (Handler : in out View_Handler;
Name : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : out ASF.Components.Root.UIViewRoot) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos > 0 then
Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View);
else
Handler.Restore_View (Name, Context, View);
end if;
end Create_View;
-- ------------------------------
-- Render the view represented by the component tree. The view is
-- rendered using the context.
-- ------------------------------
procedure Render_View (Handler : in out View_Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
View : in ASF.Components.Root.UIViewRoot) is
pragma Unreferenced (Handler);
Root : constant access ASF.Components.Base.UIComponent'Class
:= ASF.Components.Root.Get_Root (View);
begin
if Root /= null then
Root.Encode_All (Context);
end if;
end Render_View;
-- ------------------------------
-- Get the URL suitable for encoding and rendering the view specified by the <b>View</b>
-- identifier.
-- ------------------------------
function Get_Action_URL (Handler : in View_Handler;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
View : in String) return String is
use Ada.Strings.Unbounded;
Pos : constant Natural := Util.Strings.Rindex (View, '.');
Context_Path : constant String := Context.Get_Request.Get_Context_Path;
begin
if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then
return Context_Path & View (View'First .. Pos - 1) & To_String (Handler.View_Ext);
end if;
if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then
return Context_Path & View;
end if;
return Context_Path & View;
end Get_Action_URL;
-- ------------------------------
-- Get the URL for redirecting the user to the specified view.
-- ------------------------------
function Get_Redirect_URL (Handler : in View_Handler;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
View : in String) return String is
Pos : constant Natural := Util.Strings.Rindex (View, '?');
begin
if Pos > 0 then
return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1))
& View (Pos .. View'Last);
else
return Handler.Get_Action_URL (Context, View);
end if;
end Get_Redirect_URL;
-- ------------------------------
-- Initialize the view handler.
-- ------------------------------
procedure Initialize (Handler : out View_Handler;
Components : access ASF.Factory.Component_Factory;
Conf : in Config) is
use ASF.Views;
use Ada.Strings.Unbounded;
begin
Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM));
Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM));
Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM));
Facelets.Initialize (Factory => Handler.Facelets,
Components => Components,
Paths => To_String (Handler.Paths),
Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM),
Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM),
Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM));
end Initialize;
-- ------------------------------
-- Closes the view handler
-- ------------------------------
procedure Close (Handler : in out View_Handler) is
use ASF.Views;
begin
Facelets.Clear_Cache (Handler.Facelets);
end Close;
-- ------------------------------
-- Set the extension mapping rule to find the facelet file from
-- the name.
-- ------------------------------
procedure Set_Extension_Mapping (Handler : in out View_Handler;
From : in String;
Into : in String) is
use Ada.Strings.Unbounded;
begin
Handler.View_Ext := To_Unbounded_String (From);
Handler.File_Ext := To_Unbounded_String (Into);
end Set_Extension_Mapping;
end ASF.Applications.Views;
|
Fix get_Redirect_URL to handler view parameters
|
Fix get_Redirect_URL to handler view parameters
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
11391cba071cc4308fc56443852572b0ca6052c0
|
src/gen-artifacts-docs.ads
|
src/gen-artifacts-docs.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Gen.Model.Packages;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_SEE : constant String := "see";
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE);
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type Document_Formatter is abstract tagged null record;
type Document_Formatter_Access is access all Document_Formatter'Class;
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Vectors.Vector;
Was_Included : Boolean := False;
Formatter : Document_Formatter_Access;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is abstract;
-- Start a new document.
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is abstract;
-- Write a line in the target document formatting the line if necessary.
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is abstract;
-- Finish the document.
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is abstract;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
end record;
end Gen.Artifacts.Docs;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Gen.Model.Packages;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_SEE : constant String := "see";
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE);
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type Document_Formatter is abstract tagged null record;
type Document_Formatter_Access is access all Document_Formatter'Class;
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Vectors.Vector;
Was_Included : Boolean := False;
Formatter : Document_Formatter_Access;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is abstract;
-- Start a new document.
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is abstract;
-- Write a line in the target document formatting the line if necessary.
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is abstract;
-- Finish the document.
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is abstract;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
Formatter : Document_Formatter_Access;
end record;
end Gen.Artifacts.Docs;
|
Add a Formatter member to the Artifact type
|
Add a Formatter member to the Artifact type
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
11e1812f01b18ffb5d2eefc4297eee994824da54
|
mat/src/mat-targets.ads
|
mat/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- Targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with Ada.Strings.Unbounded;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
package MAT.Targets is
-- type Target_Type is tagged limited private;
type Target_Type is tagged limited record
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
end record;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
--
-- private
--
-- type Target_Type is tagged limited record
-- Memory : MAT.Memory.Targets.Target_Memory;
-- end record;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
-- type Target_Type is tagged limited private;
type Target_Type is tagged limited record
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
--
-- private
--
-- type Target_Type is tagged limited record
-- Memory : MAT.Memory.Targets.Target_Memory;
-- end record;
end MAT.Targets;
|
Add a console instance to the target
|
Add a console instance to the target
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
19ee74a727cf814f830573b9d44cfd00aa77283a
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.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 ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
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.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.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.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;
|
Add the comments module unit tests
|
Add the comments module unit tests
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
658598dbc64be7c17c30d8ae25cc7715e5b87003
|
regtests/asf-applications-views-tests.adb
|
regtests/asf-applications-views-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Core;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables.Default;
with ASF.Contexts.Writer.Tests;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
use ASF.Contexts.Writer.Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf);
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
-- Writer : aliased Test_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;
begin
-- 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", 16384);
-- Set_Current (Context'Unchecked_Access);
-- H.Restore_View (View_Name, Context, View);
--
-- H.Render_View (Context, View);
-- Writer.Flush;
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Core;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables.Default;
with ASF.Contexts.Writer.Tests;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
use ASF.Contexts.Writer.Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf, App_Factory);
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
fix the unit test and cleanup
|
fix the unit test and cleanup
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a0d2398609fa663a9e728737267d38f6dcbc8e6f
|
regtests/dlls/util-systems-dlls-tests.ads
|
regtests/dlls/util-systems-dlls-tests.ads
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Systems.Dlls.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the loading a shared library.
procedure Test_Load (T : in out Test);
-- Test getting a shared library symbol.
procedure Test_Get_Symbol (T : in out Test);
end Util.Systems.Dlls.Tests;
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Systems.DLLs.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the loading a shared library.
procedure Test_Load (T : in out Test);
-- Test getting a shared library symbol.
procedure Test_Get_Symbol (T : in out Test);
end Util.Systems.DLLs.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
b6eaeed5fa6f6e38c1af2bfc6f3c7fdf47c4f0f6
|
regtests/util-serialize-io-json-tests.ads
|
regtests/util-serialize-io-json-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
-- Generate some output stream for the test.
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class);
-- Test the JSON output stream generation.
procedure Test_Output (T : in out Test);
-- Test the JSON output stream generation (simple JSON documents).
procedure Test_Simple_Output (T : in out Test);
-- Test reading a JSON content into an Object tree.
procedure Test_Read (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
-- Generate some output stream for the test.
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class);
-- Test the JSON output stream generation.
procedure Test_Output (T : in out Test);
-- Test the JSON output stream generation (simple JSON documents).
procedure Test_Simple_Output (T : in out Test);
-- Test the JSON output stream generation and parsing for nullable basic types.
procedure Test_Nullable (T : in out Test);
-- Test reading a JSON content into an Object tree.
procedure Test_Read (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
Declare the Test_Nullable procedure
|
Declare the Test_Nullable procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1e28dc779555a0a6d2e9acf404f7075db64b6616
|
ARM/STMicro/STM32/drivers/stm32f4-syscfg.adb
|
ARM/STMicro/STM32/drivers/stm32f4-syscfg.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f407xx.h et al. --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief CMSIS STM32F407xx Device Peripheral Access Layer Header File. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- microcontrollers from ST Microelectronics.
with STM32F4.EXTI;
package body STM32F4.SYSCFG is
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pin : GPIO_Pin)
is
CR_Index : Integer range EXTI_Control_Registers'Range;
EXTI_Index : Integer range EXTI_n_List'Range;
Port_Name : constant GPIO_Port_Id := As_GPIO_Port_Id (Port);
begin
-- First we find the control register, of the four possible, that
-- contains the EXTI_n value for pin 'n' specified by the Pin parameter.
-- In effect, this is what we are doing for the EXTICR index:
-- case GPIO_Pin'Pos (Pin) is
-- when 0 .. 3 => CR_Index := 0;
-- when 4 .. 7 => CR_Index := 1;
-- when 8 .. 11 => CR_Index := 2;
-- when 12 .. 15 => CR_Index := 3;
-- end case;
-- Note that that means we are dependent upon the order of the Pin
-- declarations because we require GPIO_Pin'Pos(Pin_n) to be 'n', ie
-- Pin_0 should be at position 0, Pin_1 at position 1, and so forth.
CR_Index := GPIO_Pin'Pos (Pin) / 4;
-- Now we must find which EXTI_n value to use, of the four possible,
-- within the control register. We are depending on the GPIO_Port type
-- being an enumeration and that the enumeral order is alphabetical on
-- the Port letter, such that in effect GPIO_A'Pos = 0, GPIO_B'Pos = 1,
-- and so on.
EXTI_Index := GPIO_Port_Id'Pos (Port_Name) mod 4; -- ie 0 .. 3
-- Finally we assign the port 'number' to the EXTI_n value within the
-- control register. We depend upon the Port enumerals' underlying
-- numeric representation values matching what the hardware expects,
-- that is, the values 0 .. n-1, which we get automatically unless
-- overridden.
SYSCFG.EXTICR (CR_Index).EXTI (EXTI_Index) := Port_Name;
end Connect_External_Interrupt;
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pins : GPIO_Pins)
is
begin
for Pin of Pins loop
Connect_External_Interrupt (Port, Pin);
end loop;
end Connect_External_Interrupt;
------------------------------
-- Clear_External_Interrupt --
------------------------------
procedure Clear_External_Interrupt (Pin : GPIO_Pin) is
use STM32F4.EXTI;
begin
Clear_External_Interrupt (External_Line_Number'Val (GPIO_Pin'Pos (Pin)));
end Clear_External_Interrupt;
---------------------
-- As_GPIO_Port_Id --
---------------------
function As_GPIO_Port_Id (Port : GPIO_Port) return GPIO_Port_Id is
begin
-- TODO: rather ugly to have this board-specific range here
if Port'Address = GPIOA_Base then
return GPIO_Port_A;
elsif Port'Address = GPIOB_Base then
return GPIO_Port_B;
elsif Port'Address = GPIOC_Base then
return GPIO_Port_C;
elsif Port'Address = GPIOD_Base then
return GPIO_Port_D;
elsif Port'Address = GPIOE_Base then
return GPIO_Port_E;
elsif Port'Address = GPIOF_Base then
return GPIO_Port_F;
elsif Port'Address = GPIOG_Base then
return GPIO_Port_G;
elsif Port'Address = GPIOH_Base then
return GPIO_Port_H;
elsif Port'Address = GPIOI_Base then
return GPIO_Port_I;
elsif Port'Address = GPIOJ_Base then
return GPIO_Port_J;
elsif Port'Address = GPIOK_Base then
return GPIO_Port_K;
else
raise Program_Error;
end if;
end As_GPIO_Port_Id;
end STM32F4.SYSCFG;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f407xx.h et al. --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief CMSIS STM32F407xx Device Peripheral Access Layer Header File. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- microcontrollers from ST Microelectronics.
with STM32F4.EXTI;
package body STM32F4.SYSCFG is
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pin : GPIO_Pin)
is
CR_Index : Integer range EXTI_Control_Registers'Range;
EXTI_Index : Integer range EXTI_n_List'Range;
Port_Name : constant GPIO_Port_Id := As_GPIO_Port_Id (Port);
begin
-- First we find the control register, of the four possible, that
-- contains the EXTI_n value for pin 'n' specified by the Pin parameter.
-- In effect, this is what we are doing for the EXTICR index:
-- case GPIO_Pin'Pos (Pin) is
-- when 0 .. 3 => CR_Index := 0;
-- when 4 .. 7 => CR_Index := 1;
-- when 8 .. 11 => CR_Index := 2;
-- when 12 .. 15 => CR_Index := 3;
-- end case;
-- Note that that means we are dependent upon the order of the Pin
-- declarations because we require GPIO_Pin'Pos(Pin_n) to be 'n', ie
-- Pin_0 should be at position 0, Pin_1 at position 1, and so forth.
CR_Index := GPIO_Pin'Pos (Pin) / 4;
-- Now we must find which EXTI_n value to use, of the four possible,
-- within the control register.
EXTI_Index := GPIO_Pin'Pos (Pin) mod 4; -- ie 0 .. 3
-- Finally we assign the port 'number' to the EXTI_n value within the
-- control register. We depend upon the Port enumerals' underlying
-- numeric representation values matching what the hardware expects,
-- that is, the values 0 .. n-1, which we get automatically unless
-- overridden.
SYSCFG.EXTICR (CR_Index).EXTI (EXTI_Index) := Port_Name;
end Connect_External_Interrupt;
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pins : GPIO_Pins)
is
begin
for Pin of Pins loop
Connect_External_Interrupt (Port, Pin);
end loop;
end Connect_External_Interrupt;
------------------------------
-- Clear_External_Interrupt --
------------------------------
procedure Clear_External_Interrupt (Pin : GPIO_Pin) is
use STM32F4.EXTI;
begin
Clear_External_Interrupt (External_Line_Number'Val (GPIO_Pin'Pos (Pin)));
end Clear_External_Interrupt;
---------------------
-- As_GPIO_Port_Id --
---------------------
function As_GPIO_Port_Id (Port : GPIO_Port) return GPIO_Port_Id is
begin
-- TODO: rather ugly to have this board-specific range here
if Port'Address = GPIOA_Base then
return GPIO_Port_A;
elsif Port'Address = GPIOB_Base then
return GPIO_Port_B;
elsif Port'Address = GPIOC_Base then
return GPIO_Port_C;
elsif Port'Address = GPIOD_Base then
return GPIO_Port_D;
elsif Port'Address = GPIOE_Base then
return GPIO_Port_E;
elsif Port'Address = GPIOF_Base then
return GPIO_Port_F;
elsif Port'Address = GPIOG_Base then
return GPIO_Port_G;
elsif Port'Address = GPIOH_Base then
return GPIO_Port_H;
elsif Port'Address = GPIOI_Base then
return GPIO_Port_I;
elsif Port'Address = GPIOJ_Base then
return GPIO_Port_J;
elsif Port'Address = GPIOK_Base then
return GPIO_Port_K;
else
raise Program_Error;
end if;
end As_GPIO_Port_Id;
end STM32F4.SYSCFG;
|
Correct EXTI_Index computation in Connect_External_Interrupt
|
Correct EXTI_Index computation in Connect_External_Interrupt
|
Ada
|
bsd-3-clause
|
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library
|
bfd39d488b87af0754cb0b5e7516cfbc74591e60
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
Map : Role_Map;
begin
M.Create_Role (Name => "manager",
Role => Role);
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
M.Set_Roles ("admin", Map);
end Test_Set_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Role);
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
T.Assert (not Map (Role), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Role), "The admin role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Check that the given role is set after Set_Roles
|
Check that the given role is set after Set_Roles
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
500373cc8aa887b4695287e3fbd72fff49a148ca
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
pragma Unreferenced (Format);
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref) is
begin
if Wiki.Nodes.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
use Wiki.Nodes.Lists;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
pragma Unreferenced (Format);
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref) is
begin
if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
Update to use the new Node_List_Ref reference
|
Update to use the new Node_List_Ref reference
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
684fcb8896b4d0af8b1c5499070d2a083decb412
|
src/gen-commands-info.adb
|
src/gen-commands-info.adb
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
end Print_Project_List;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
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);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
end Print_Project_List;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
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);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
55b282bd44fe23f6d4956ca81ace82f2020da9b2
|
src/security-auth-oauth-googleplus.adb
|
src/security-auth-oauth-googleplus.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth-googleplus -- Google+ OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.JWT;
package body Security.Auth.OAuth.Googleplus is
use Util.Log;
Log : constant Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth.Googleplus");
-- ------------------------------
-- Verify the OAuth access token and retrieve information about the user.
-- ------------------------------
overriding
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
pragma Unreferenced (Assoc, Request);
begin
-- The token returned by Google+ must contain an id_token.
if not (Token.all in Security.OAuth.Clients.OpenID_Token'Class) then
Log.Warn ("Invalid token instance created: missing the id_token");
Set_Result (Result, INVALID_SIGNATURE, "invalid access token returned");
return;
end if;
-- The id_token is a JWT token that must be decoded and verified.
-- See https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken
-- It contains information to identify the user.
declare
T : constant Security.OAuth.Clients.OpenID_Token_Access :=
Security.OAuth.Clients.OpenID_Token'Class (Token.all)'Access;
Info : constant Security.OAuth.JWT.Token := Security.OAuth.JWT.Decode (T.Get_Id_Token);
begin
-- Verify that the JWT token concerns our application.
if Security.OAuth.JWT.Get_Audience (Info) /= Realm.App.Get_Application_Identifier then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was granted for another application");
return;
-- Verify that the issuer is Google+
elsif Security.OAuth.JWT.Get_Issuer (Info) /= Realm.Issuer then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was not generated by the expected authority");
return;
end if;
Result.Identity := To_Unbounded_String ("https://accounts.google.com/");
Append (Result.Identity, Security.OAuth.JWT.Get_Subject (Info));
Result.Claimed_Id := Result.Identity;
-- The email is optional and depends on the scope.
Result.Email := To_Unbounded_String (Security.OAuth.JWT.Get_Claim (Info, "email", ""));
Set_Result (Result, AUTHENTICATED, "authenticated");
end;
end Verify_Access_Token;
end Security.Auth.OAuth.Googleplus;
|
-----------------------------------------------------------------------
-- security-auth-oauth-googleplus -- Google+ OAuth based authentication
-- Copyright (C) 2013, 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.Log.Loggers;
with Security.OAuth.JWT;
package body Security.Auth.OAuth.Googleplus is
use Util.Log;
Log : constant Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth.Googleplus");
-- ------------------------------
-- Verify the OAuth access token and retrieve information about the user.
-- ------------------------------
overriding
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
pragma Unreferenced (Request);
begin
-- The token returned by Google+ must contain an id_token.
if not (Token.all in Security.OAuth.Clients.OpenID_Token'Class) then
Log.Warn ("Invalid token instance created: missing the id_token");
Set_Result (Result, INVALID_SIGNATURE, "invalid access token returned");
return;
end if;
-- The id_token is a JWT token that must be decoded and verified.
-- See https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken
-- It contains information to identify the user.
declare
T : constant Security.OAuth.Clients.OpenID_Token_Access :=
Security.OAuth.Clients.OpenID_Token'Class (Token.all)'Access;
Info : constant Security.OAuth.JWT.Token := Security.OAuth.JWT.Decode (T.Get_Id_Token);
begin
-- Verify that the JWT token concerns our application.
if Security.OAuth.JWT.Get_Audience (Info) /= Realm.App.Get_Application_Identifier then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was granted for another application");
return;
-- Verify that the issuer is Google+
elsif Security.OAuth.JWT.Get_Issuer (Info) /= Realm.Issuer then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was not generated by the expected authority");
return;
-- Verify that the nonce we received matches our nonce.
elsif Security.OAuth.JWT.Get_Claim (Info, "nonce") /= Assoc.Nonce then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was not generated with the expected nonce");
return;
end if;
Result.Identity := To_Unbounded_String ("https://accounts.google.com/");
Append (Result.Identity, Security.OAuth.JWT.Get_Subject (Info));
Result.Claimed_Id := Result.Identity;
-- The email is optional and depends on the scope.
Result.Email := To_Unbounded_String (Security.OAuth.JWT.Get_Claim (Info, "email", ""));
Set_Result (Result, AUTHENTICATED, "authenticated");
end;
end Verify_Access_Token;
end Security.Auth.OAuth.Googleplus;
|
Verify the nonce that we receive
|
Verify the nonce that we receive
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
26d89d775dd4b5bbbf84100d784137c3ac9cc6b1
|
src/security-oauth-file_registry.ads
|
src/security-oauth-file_registry.ads
|
-----------------------------------------------------------------------
-- security-oauth-file_registry -- File Based Application and Realm
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Util.Properties;
with Security.OAuth.Servers;
private with Util.Strings.Maps;
private with Security.Random;
package Security.OAuth.File_Registry is
type File_Principal is new Security.Principal with private;
type File_Principal_Access is access all File_Principal'Class;
-- Get the principal name.
overriding
function Get_Name (From : in File_Principal) return String;
type File_Application_Manager is new Servers.Application_Manager with private;
-- 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.
overriding
function Find_Application (Realm : in File_Application_Manager;
Client_Id : in String) return Servers.Application'Class;
-- Add the application to the application repository.
procedure Add_Application (Realm : in out File_Application_Manager;
App : in Servers.Application);
-- Load from the properties the definition of applications. The list of applications
-- is controled by the property <prefix>.list which contains a comma separated list of
-- application names or ids. The application definition are represented by properties
-- of the form:
-- <prefix>.<app>.client_id
-- <prefix>.<app>.client_secret
-- <prefix>.<app>.callback_url
procedure Load (Realm : in out File_Application_Manager;
Props : in Util.Properties.Manager'Class;
Prefix : in String);
procedure Load (Realm : in out File_Application_Manager;
Path : in String;
Prefix : in String);
type File_Realm_Manager is limited new Servers.Realm_Manager with private;
-- 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.
overriding
procedure Authenticate (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean);
-- 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.
overriding
function Authorize (Realm : in File_Realm_Manager;
App : in Servers.Application'Class;
Scope : in String;
Auth : in Principal_Access) return String;
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access);
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Principal_Access);
overriding
procedure Revoke (Realm : in out File_Realm_Manager;
Auth : in Principal_Access);
-- Crypt the password using the given salt and return the string composed with
-- the salt in clear text and the crypted password.
function Crypt_Password (Realm : in File_Realm_Manager;
Salt : in String;
Password : in String) return String;
-- Load from the properties the definition of users. The list of users
-- is controled by the property <prefix>.list which contains a comma separated list of
-- users names or ids. The user definition are represented by properties
-- of the form:
-- <prefix>.<user>.username
-- <prefix>.<user>.password
-- <prefix>.<user>.salt
-- When a 'salt' property is defined, it is assumed that the password is encrypted using
-- the salt and SHA1 and base64url. Otherwise, the password is in clear text.
procedure Load (Realm : in out File_Realm_Manager;
Props : in Util.Properties.Manager'Class;
Prefix : in String);
procedure Load (Realm : in out File_Realm_Manager;
Path : in String;
Prefix : in String);
-- Add a username with the associated password.
procedure Add_User (Realm : in out File_Realm_Manager;
Username : in String;
Password : in String);
private
use Ada.Strings.Unbounded;
package Application_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Servers.Application,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => Servers."=");
package Token_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Principal_Access,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
package User_Maps renames Util.Strings.Maps;
type File_Principal is new Security.Principal with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Application_Manager is new Servers.Application_Manager with record
Applications : Application_Maps.Map;
end record;
type File_Realm_Manager is limited new Servers.Realm_Manager with record
Users : User_Maps.Map;
Tokens : Token_Maps.Map;
Random : Security.Random.Generator;
Token_Bits : Positive := 256;
end record;
end Security.OAuth.File_Registry;
|
-----------------------------------------------------------------------
-- security-oauth-file_registry -- File Based Application and Realm
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Util.Properties;
with Security.OAuth.Servers;
with Security.Permissions;
private with Util.Strings.Maps;
private with Security.Random;
package Security.OAuth.File_Registry is
type File_Principal is new Servers.Principal with private;
type File_Principal_Access is access all File_Principal'Class;
-- Get the principal name.
overriding
function Get_Name (From : in File_Principal) return String;
-- Check if the permission was granted.
overriding
function Has_Permission (Auth : in File_Principal;
Permission : in Security.Permissions.Permission_Index)
return Boolean;
type File_Application_Manager is new Servers.Application_Manager with private;
-- 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.
overriding
function Find_Application (Realm : in File_Application_Manager;
Client_Id : in String) return Servers.Application'Class;
-- Add the application to the application repository.
procedure Add_Application (Realm : in out File_Application_Manager;
App : in Servers.Application);
-- Load from the properties the definition of applications. The list of applications
-- is controled by the property <prefix>.list which contains a comma separated list of
-- application names or ids. The application definition are represented by properties
-- of the form:
-- <prefix>.<app>.client_id
-- <prefix>.<app>.client_secret
-- <prefix>.<app>.callback_url
procedure Load (Realm : in out File_Application_Manager;
Props : in Util.Properties.Manager'Class;
Prefix : in String);
procedure Load (Realm : in out File_Application_Manager;
Path : in String;
Prefix : in String);
type File_Realm_Manager is limited new Servers.Realm_Manager with private;
-- 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.
overriding
procedure Authenticate (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Servers.Principal_Access;
Cacheable : out Boolean);
-- 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.
overriding
function Authorize (Realm : in File_Realm_Manager;
App : in Servers.Application'Class;
Scope : in String;
Auth : in Servers.Principal_Access) return String;
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Username : in String;
Password : in String;
Auth : out Servers.Principal_Access);
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Servers.Principal_Access);
overriding
procedure Revoke (Realm : in out File_Realm_Manager;
Auth : in Servers.Principal_Access);
-- Crypt the password using the given salt and return the string composed with
-- the salt in clear text and the crypted password.
function Crypt_Password (Realm : in File_Realm_Manager;
Salt : in String;
Password : in String) return String;
-- Load from the properties the definition of users. The list of users
-- is controled by the property <prefix>.list which contains a comma separated list of
-- users names or ids. The user definition are represented by properties
-- of the form:
-- <prefix>.<user>.username
-- <prefix>.<user>.password
-- <prefix>.<user>.salt
-- When a 'salt' property is defined, it is assumed that the password is encrypted using
-- the salt and SHA1 and base64url. Otherwise, the password is in clear text.
procedure Load (Realm : in out File_Realm_Manager;
Props : in Util.Properties.Manager'Class;
Prefix : in String);
procedure Load (Realm : in out File_Realm_Manager;
Path : in String;
Prefix : in String);
-- Add a username with the associated password.
procedure Add_User (Realm : in out File_Realm_Manager;
Username : in String;
Password : in String);
private
use Ada.Strings.Unbounded;
package Application_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Servers.Application,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => Servers."=");
package Token_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Principal_Access,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
package User_Maps renames Util.Strings.Maps;
type File_Principal is new Servers.Principal with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Perms : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET;
end record;
type File_Application_Manager is new Servers.Application_Manager with record
Applications : Application_Maps.Map;
end record;
type File_Realm_Manager is limited new Servers.Realm_Manager with record
Users : User_Maps.Map;
Tokens : Token_Maps.Map;
Random : Security.Random.Generator;
Token_Bits : Positive := 256;
end record;
end Security.OAuth.File_Registry;
|
Change the File_Principal to implement the OAuth principal interface
|
Change the File_Principal to implement the OAuth principal interface
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f174e52c0f172d8fe7e8f846106aecc031552442
|
awa/src/awa-modules.adb
|
awa/src/awa-modules.adb
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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.Services.Contexts;
with AWA.Applications;
package body AWA.Modules is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- 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_Manager;
Name : String;
Default : String := "") return String is
begin
return Plugin.Module.all.Get_Config (Name, 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_Manager;
Config : in ASF.Applications.Config_Param) return String is
begin
return Plugin.Module.all.Get_Config (Config);
end Get_Config;
-- ------------------------------
-- 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 name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Plugin : in Module;
Name : in String;
Default : in Boolean := False) return Boolean is
Value : constant String := Plugin.Config.Get (Name, Boolean'Image (Default));
begin
if Value in "yes" | "true" | "1" then
return True;
else
return False;
end if;
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
type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null record;
overriding
function Get_Value (Resolver : Event_ELResolver;
Context : EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return Util.Beans.Objects.Object;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Event_ELResolver;
Context : EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return Util.Beans.Objects.Object is
begin
if Base /= null then
return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base,
Name);
else
return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), ""));
end if;
end Get_Value;
Resolver : aliased Event_ELResolver;
Context : EL.Contexts.Default.Default_Context;
Value : constant String := Plugin.Get_Config (Name, Default);
begin
Context.Set_Resolver (Resolver'Unchecked_Access);
return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context),
Context);
exception
when E : others =>
Log.Error ("Invalid parameter ", E, True);
return EL.Expressions.Create_Expression ("", Context);
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
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
return ASC.Get_Session (Ctx);
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (Manager : Module)
return ADO.Sessions.Master_Session is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
return ASC.Get_Master_Session (Ctx);
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, 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 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.Services.Contexts;
with AWA.Applications;
package body AWA.Modules is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- 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_Manager;
Name : String;
Default : String := "") return String is
begin
return Plugin.Module.all.Get_Config (Name, 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_Manager;
Config : in ASF.Applications.Config_Param) return String is
begin
return Plugin.Module.all.Get_Config (Config);
end Get_Config;
-- ------------------------------
-- 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 name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Plugin : in Module;
Name : in String;
Default : in Boolean := False) return Boolean is
Value : constant String := Plugin.Config.Get (Name, Boolean'Image (Default));
begin
if Value in "yes" | "true" | "1" then
return True;
else
return False;
end if;
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
type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null record;
overriding
function Get_Value (Resolver : Event_ELResolver;
Context : EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return Util.Beans.Objects.Object;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Event_ELResolver;
Context : EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return Util.Beans.Objects.Object is
begin
if Base /= null then
return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base,
Name);
else
return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), ""));
end if;
end Get_Value;
Resolver : aliased Event_ELResolver;
Context : EL.Contexts.Default.Default_Context;
Value : constant String := Plugin.Get_Config (Name, Default);
begin
Context.Set_Resolver (Resolver'Unchecked_Access);
return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context),
Context);
exception
when E : others =>
Log.Error ("Invalid parameter ", E, True);
return EL.Expressions.Create_Expression ("", Context);
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
pragma Unreferenced (Manager);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
return ASC.Get_Session (Ctx);
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (Manager : Module)
return ADO.Sessions.Master_Session is
pragma Unreferenced (Manager);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
return ASC.Get_Master_Session (Ctx);
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;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
da69fd8bfdc244c3f6474791e141cc6b5b3aaf27
|
matp/src/frames/mat-frames.ads
|
matp/src/frames/mat-frames.ads
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
package MAT.Frames is
Not_Found : exception;
type Frame_Type is private;
subtype Frame_Table is MAT.Events.Frame_Table;
-- Return the parent frame.
function Parent (Frame : in Frame_Type) return Frame_Type;
-- Returns the backtrace of the current frame (up to the root).
-- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value.
function Backtrace (Frame : in Frame_Type;
Max_Level : in Natural := 0) return Frame_Table;
-- Returns all the direct calls made by the current frame.
function Calls (Frame : in Frame_Type) return Frame_Table;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (Frame : in Frame_Type) return Natural;
-- Create a root for stack frame representation.
function Create_Root return Frame_Type;
-- Destroy the frame tree recursively.
procedure Destroy (Frame : in out Frame_Type);
-- Release the frame when its reference is no longer necessary.
procedure Release (Frame : in Frame_Type);
-- 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 Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (Frame : in Frame_Type;
Pc : in MAT.Types.Target_Addr) return Frame_Type;
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural);
private
Frame_Group_Size : constant Natural := 4;
subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size;
subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last);
type Frame;
type Frame_Type is access all Frame;
type Frame is record
Parent : Frame_Type := null;
Next : Frame_Type := null;
Children : Frame_Type := null;
Used : Natural := 0;
Depth : Natural := 0;
Calls : Mini_Frame_Table;
Local_Depth : Local_Depth_Type := 0;
end record;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- 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.Types;
with MAT.Events;
package MAT.Frames is
Not_Found : exception;
type Frame_Type is private;
subtype Frame_Table is MAT.Events.Frame_Table;
-- Return the parent frame.
function Parent (Frame : in Frame_Type) return Frame_Type;
-- Returns the backtrace of the current frame (up to the root).
-- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value.
function Backtrace (Frame : in Frame_Type;
Max_Level : in Natural := 0) return Frame_Table;
-- Returns all the direct calls made by the current frame.
function Calls (Frame : in Frame_Type) return Frame_Table;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (Frame : in Frame_Type) return Natural;
-- Create a root for stack frame representation.
function Create_Root return Frame_Type;
-- Destroy the frame tree recursively.
procedure Destroy (Frame : in out Frame_Type);
-- Release the frame when its reference is no longer necessary.
procedure Release (Frame : in Frame_Type);
-- 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 Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (Frame : in Frame_Type;
Pc : in MAT.Types.Target_Addr) return Frame_Type;
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural);
-- Check whether the frame contains a call to the function described by the address range.
function In_Function (Frame : in Frame_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) return Boolean;
private
Frame_Group_Size : constant Natural := 4;
subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size;
subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last);
type Frame;
type Frame_Type is access all Frame;
type Frame is record
Parent : Frame_Type := null;
Next : Frame_Type := null;
Children : Frame_Type := null;
Used : Natural := 0;
Depth : Natural := 0;
Calls : Mini_Frame_Table;
Local_Depth : Local_Depth_Type := 0;
end record;
end MAT.Frames;
|
Declare the In_Function function to check if the frame contains calls of a given function
|
Declare the In_Function function to check if the frame contains calls of a given function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.