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
|
---|---|---|---|---|---|---|---|---|---|
5341d6e5afa0957eeccc9b019660448f7fa55159
|
src/util-encoders-base64.ads
|
src/util-encoders-base64.ads
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- Copyright (C) 2009, 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.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
pragma Preelaborate;
-- Encode the 64-bit value to LEB128 and then base64url.
function Encode (Value : in Interfaces.Unsigned_64) return String;
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
function Decode (Value : in String) return Interfaces.Unsigned_64;
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 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 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);
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean);
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Encoder return Transformer_Access;
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary 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 Decoder;
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);
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean);
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Decoder return Transformer_Access;
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
pragma Preelaborate;
-- Encode the 64-bit value to LEB128 and then base64url.
function Encode (Value : in Interfaces.Unsigned_64) return String;
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
function Decode (Value : in String) return Interfaces.Unsigned_64;
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 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);
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean);
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Encoder return Transformer_Access;
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary 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 Decoder;
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);
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean);
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Decoder return Transformer_Access;
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4e75c0329d769e47182d82aa953654398a9b602d
|
regtests/util-texts-builders_tests.ads
|
regtests/util-texts-builders_tests.ads
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Texts.Builders_Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the length operation.
procedure Test_Length (T : in out Test);
-- Test the append operation.
procedure Test_Append (T : in out Test);
-- Test the append operation.
procedure Test_Inline_Append (T : in out Test);
-- Test the iterate operation.
procedure Test_Iterate (T : in out Test);
-- Test the iterate operation.
procedure Test_Inline_Iterate (T : in out Test);
-- Test the clear operation.
procedure Test_Clear (T : in out Test);
-- Test the tail operation.
procedure Test_Tail (T : in out Test);
-- Test the append and iterate performance.
procedure Test_Perf (T : in out Test);
end Util.Texts.Builders_Tests;
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Texts.Builders_Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the length operation.
procedure Test_Length (T : in out Test);
-- Test the append operation.
procedure Test_Append (T : in out Test);
-- Test the append operation.
procedure Test_Inline_Append (T : in out Test);
-- Test the iterate operation.
procedure Test_Iterate (T : in out Test);
-- Test the iterate operation.
procedure Test_Inline_Iterate (T : in out Test);
-- Test the Find generic operation.
procedure Test_Find (T : in out Test);
-- Test the clear operation.
procedure Test_Clear (T : in out Test);
-- Test the tail operation.
procedure Test_Tail (T : in out Test);
-- Test the append and iterate performance.
procedure Test_Perf (T : in out Test);
end Util.Texts.Builders_Tests;
|
Declare the Test_Find procedure
|
Declare the Test_Find procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
759e0d020a4b87732a23efbfc586ab1edd78a7fb
|
mat/src/memory/mat-memory-readers.ads
|
mat/src/memory/mat-memory-readers.ads
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
-- with MAT.Ipc;
with Util.Events;
with MAT.Readers;
with MAT.Memory.Targets;
-- with MAT.Memory.Clients;
-- with MAT.Ipc.Clients;
-- with MAT.Events; use MAT.Events;
package MAT.Memory.Readers is
type Memory_Servant is new MAT.Readers.Reader_Base with record
Data : MAT.Memory.Targets.Client_Memory;
-- Slots : Client_Memory_Ref;
-- Impl : Client_Memory_Ref;
end record;
type Memory_Reader_Access is access all Memory_Servant'Class;
-- The memory servant is a proxy for the generic communication
-- channel to process incomming events (such as memory allocations).
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message);
-- Register the reader to extract and analyze memory events.
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access);
end MAT.Memory.Readers;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
-- with MAT.Ipc;
with Util.Events;
with MAT.Readers;
with MAT.Memory.Targets;
-- with MAT.Memory.Clients;
-- with MAT.Ipc.Clients;
-- with MAT.Events; use MAT.Events;
package MAT.Memory.Readers is
type Memory_Servant is new MAT.Readers.Reader_Base with record
Data : MAT.Memory.Targets.Target_Memory;
-- Slots : Client_Memory_Ref;
-- Impl : Client_Memory_Ref;
end record;
type Memory_Reader_Access is access all Memory_Servant'Class;
-- The memory servant is a proxy for the generic communication
-- channel to process incomming events (such as memory allocations).
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message);
-- Register the reader to extract and analyze memory events.
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access);
end MAT.Memory.Readers;
|
Rename Client_Memory into Target_Memory
|
Rename Client_Memory into Target_Memory
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
89671b58bfe23174debacc207afbb95060c27ee4
|
regtests/util_harness.adb
|
regtests/util_harness.adb
|
-----------------------------------------------------------------------
-- Util -- Utilities
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Testsuite;
with Util.Tests;
procedure Util_Harness is
procedure Harness is new Util.Tests.Harness (Util.Testsuite.Suite);
begin
Harness ("util-tests.xml");
end Util_Harness;
|
-----------------------------------------------------------------------
-- Util -- Utilities
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Testsuite;
with Util.Tests;
with Util.Properties;
procedure Util_Harness is
procedure Initialize (Props : in Util.Properties.Manager);
procedure Harness is new Util.Tests.Harness (Util.Testsuite.Suite, Initialize);
procedure Initialize (Props : in Util.Properties.Manager) is
pragma Unreferenced (Props);
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
begin
if not Ada.Directories.Exists (Path) then
Ada.Directories.Create_Directory (Path);
end if;
end Initialize;
begin
Harness ("util-tests.xml");
end Util_Harness;
|
Fix running the testsuite with AUnit: create the 'regtests/result' directory if it does not exist
|
Fix running the testsuite with AUnit: create the 'regtests/result' directory if it does not exist
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d2d0a3ece3432ed5a7510f2189d267e5bdf8623e
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with ASF.Helpers.Beans;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Components.Wikis;
package AWA.Wikis.Beans is
use Ada.Strings.Wide_Wide_Unbounded;
type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Wiki_Links_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 Wiki_Links_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read page counter associated with the wiki page.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.WIKI_PAGE_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki page links.
Links : aliased Wiki_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Wiki_View_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean,
Element_Access => Wiki_View_Bean_Access);
-- Get a select item list which contains a list of wiki formats.
function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki space information.
overriding
procedure Load (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Setup the wiki page for the creation.
overriding
procedure Setup (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Version List Bean
-- ------------------------------
type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean;
Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access;
end record;
type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Version_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Version_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (Into : in out Wiki_Version_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with ASF.Helpers.Beans;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Components.Wikis;
-- == Wiki Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- == Ada Beans ==
-- @include wikis.xml
package AWA.Wikis.Beans is
use Ada.Strings.Wide_Wide_Unbounded;
type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Wiki_Links_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 Wiki_Links_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read page counter associated with the wiki page.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.WIKI_PAGE_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki page links.
Links : aliased Wiki_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Wiki_View_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean,
Element_Access => Wiki_View_Bean_Access);
-- Get a select item list which contains a list of wiki formats.
function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki space information.
overriding
procedure Load (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Setup the wiki page for the creation.
overriding
procedure Setup (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Version List Bean
-- ------------------------------
type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean;
Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access;
end record;
type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Version_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Version_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (Into : in out Wiki_Version_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
Document the wiki beans
|
Document the wiki beans
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
176666d4209b9702df6578870d24aee103bbf032
|
src/orka/interface/orka-rendering-framebuffers.ads
|
src/orka/interface/orka-rendering-framebuffers.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Ada.Containers.Indefinite_Holders;
with GL.Buffers;
with GL.Objects.Framebuffers;
with GL.Objects.Textures;
with GL.Types.Colors;
with Orka.Contexts;
with Orka.Rendering.Buffers;
with Orka.Rendering.Textures;
with Orka.Windows;
package Orka.Rendering.Framebuffers is
pragma Preelaborate;
use GL.Types;
package FB renames GL.Objects.Framebuffers;
package Textures renames GL.Objects.Textures;
subtype Color_Attachment_Point is FB.Attachment_Point
range FB.Color_Attachment_0 .. FB.Color_Attachment_15;
type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean;
-- TODO Use as formal parameter in procedure Invalidate
type Buffer_Values is record
Color : Colors.Color := (0.0, 0.0, 0.0, 0.0);
Depth : GL.Buffers.Depth := 1.0;
Stencil : GL.Buffers.Stencil_Index := 0;
end record;
type Framebuffer (Default : Boolean) is tagged private
with Type_Invariant => (if Framebuffer.Default then Framebuffer.Samples = 0);
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context'Class) return Framebuffer
with Pre => (if Samples > 0 then Context.Enabled (Contexts.Multisample)),
Post => not Create_Framebuffer'Result.Default;
function Create_Framebuffer (Width, Height : Size) return Framebuffer
with Post => not Create_Framebuffer'Result.Default;
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
with Post => Get_Default_Framebuffer'Result.Default;
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer
with Post => Create_Default_Framebuffer'Result.Default;
-----------------------------------------------------------------------------
function Width (Object : Framebuffer) return Size;
function Height (Object : Framebuffer) return Size;
function Samples (Object : Framebuffer) return Size;
function Image (Object : Framebuffer) return String;
-- Return a description of the given framebuffer
procedure Use_Framebuffer (Object : Framebuffer);
-- Use the framebuffer during rendering
--
-- The viewport is adjusted to the size of the framebuffer.
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values);
-- Set the default values for the color buffers and depth and stencil
-- buffers
function Default_Values (Object : Framebuffer) return Buffer_Values;
-- Return the current default values used when clearing the attached
-- textures
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector);
-- Set the buffer to use when blitting to another framebuffer with
-- procedure Resolve_To
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List);
-- Set the buffers to use when drawing to output variables in a fragment
-- shader, when calling procedure Clear, or when another framebuffer
-- blits its read buffer to this framebuffer with procedure Resolve_To
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True));
-- Clear the attached textures for which the mask is True using
-- the default values set with Set_Default_Values
--
-- For clearing to be effective, the following conditions must apply:
--
-- - Write mask off
-- - Rasterizer discard disabled
-- - Scissor test off or scissor rectangle set to the desired region
-- - Called procedure Set_Draw_Buffers with a list of attachments
--
-- If a combined depth/stencil texture has been attached, the depth
-- and stencil components can be cleared separately, but it may be
-- faster to clear both components.
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits);
-- Invalidate the attached textures for which the mask is True
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False))
with Pre => Object /= Subject and
(Mask.Color or Mask.Depth or Mask.Stencil) and
(if Object.Samples > 0 and Subject.Samples > 0 then
Object.Samples = Subject.Samples);
-- Copy one or more buffers, resolving multiple samples and scaling
-- if necessary, from the source to the destination framebuffer
--
-- If a buffer is specified in the mask, then the buffer should exist
-- in both framebuffers, otherwise the buffer is not copied. Call
-- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read
-- from and which buffers are written to.
--
-- Format of color buffers may differ and will be converted (if
-- supported). Formats of depth and stencil buffers must match.
--
-- Note: simultaneously resolving multiple samples and scaling
-- requires GL_EXT_framebuffer_multisample_blit_scaled.
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0)
with Pre => (not Object.Default and Texture.Allocated and
(if Attachment in Color_Attachment_Point then
(Object.Width = Texture.Width (Level) and
Object.Height = Texture.Height (Level))))
or else raise Constraint_Error with
"Cannot attach " & Rendering.Textures.Image (Texture, Level) &
" to " & Object.Image,
Post => Object.Has_Attachment (Attachment);
-- Attach the texture to the attachment point
--
-- The internal format of the texture must be valid for the given
-- attachment point.
--
-- If one of the attached textures is layered (3D, 1D/2D array, cube
-- map [array], or 2D multisampled array), then all attachments must
-- have the same kind.
--
-- All attachments of the framebuffer must have the same amount of
-- samples and they must all have fixed sample locations, or none of
-- them must have them.
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0);
-- Attach the texture to an attachment point based on the internal
-- format of the texture
--
-- Internally calls the procedure Attach above.
--
-- If the texture is color renderable, it will always be attached to
-- Color_Attachment_0. If you need to attach a texture to a different
-- color attachment point then use the other procedure Attach directly.
--
-- If the texture is layered and you want to attach a specific layer,
-- then you must call the procedure Attach_Layer below instead.
procedure Attach_Layer
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Layer : Natural;
Level : Textures.Mipmap_Level := 0)
with Pre => (not Object.Default and Texture.Allocated and
Texture.Layered and
(if Attachment in Color_Attachment_Point then
(Object.Width = Texture.Width (Level) and
Object.Height = Texture.Height (Level))))
or else raise Constraint_Error with
"Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) &
" to " & Object.Image,
Post => Object.Has_Attachment (Attachment);
-- Attach the selected 1D/2D layer of the texture to the attachment point
--
-- The internal format of the texture must be valid for the given
-- attachment point.
--
-- The texture must be layered (3D, 1D/2D array, cube
-- map [array], or 2D multisampled array).
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point)
with Pre => not Object.Default,
Post => not Object.Has_Attachment (Attachment);
-- Detach any texture currently attached to the given attachment point
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean;
Framebuffer_Incomplete_Error : exception;
private
package Attachment_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => Textures.Texture, "=" => Textures."=");
package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."=");
type Attachment_Array is array (FB.Attachment_Point)
of Attachment_Holder.Holder;
type Framebuffer (Default : Boolean) is tagged record
GL_Framebuffer : FB.Framebuffer;
Attachments : Attachment_Array;
Defaults : Buffer_Values;
Draw_Buffers : Color_Buffer_List_Holder.Holder;
Width, Height, Samples : Size;
end record;
end Orka.Rendering.Framebuffers;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Ada.Containers.Indefinite_Holders;
with GL.Buffers;
with GL.Objects.Framebuffers;
with GL.Objects.Textures;
with GL.Types.Colors;
with Orka.Contexts;
with Orka.Rendering.Buffers;
with Orka.Rendering.Textures;
with Orka.Windows;
package Orka.Rendering.Framebuffers is
pragma Preelaborate;
use GL.Types;
package FB renames GL.Objects.Framebuffers;
package Textures renames GL.Objects.Textures;
subtype Color_Attachment_Point is FB.Attachment_Point
range FB.Color_Attachment_0 .. FB.Color_Attachment_15;
type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean;
-- TODO Use as formal parameter in procedure Invalidate
type Buffer_Values is record
Color : Colors.Color := (0.0, 0.0, 0.0, 0.0);
Depth : GL.Buffers.Depth := 1.0;
Stencil : GL.Buffers.Stencil_Index := 0;
end record;
type Framebuffer (Default : Boolean) is tagged private;
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context'Class) return Framebuffer
with Pre => (if Samples > 0 then Context.Enabled (Contexts.Multisample)),
Post => not Create_Framebuffer'Result.Default;
function Create_Framebuffer (Width, Height : Size) return Framebuffer
with Post => not Create_Framebuffer'Result.Default;
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
with Post => Get_Default_Framebuffer'Result.Default;
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer
with Post => Create_Default_Framebuffer'Result.Default;
-----------------------------------------------------------------------------
function Width (Object : Framebuffer) return Size;
function Height (Object : Framebuffer) return Size;
function Samples (Object : Framebuffer) return Size;
function Image (Object : Framebuffer) return String;
-- Return a description of the given framebuffer
procedure Use_Framebuffer (Object : Framebuffer);
-- Use the framebuffer during rendering
--
-- The viewport is adjusted to the size of the framebuffer.
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values);
-- Set the default values for the color buffers and depth and stencil
-- buffers
function Default_Values (Object : Framebuffer) return Buffer_Values;
-- Return the current default values used when clearing the attached
-- textures
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector);
-- Set the buffer to use when blitting to another framebuffer with
-- procedure Resolve_To
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List);
-- Set the buffers to use when drawing to output variables in a fragment
-- shader, when calling procedure Clear, or when another framebuffer
-- blits its read buffer to this framebuffer with procedure Resolve_To
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True));
-- Clear the attached textures for which the mask is True using
-- the default values set with Set_Default_Values
--
-- For clearing to be effective, the following conditions must apply:
--
-- - Write mask off
-- - Rasterizer discard disabled
-- - Scissor test off or scissor rectangle set to the desired region
-- - Called procedure Set_Draw_Buffers with a list of attachments
--
-- If a combined depth/stencil texture has been attached, the depth
-- and stencil components can be cleared separately, but it may be
-- faster to clear both components.
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits);
-- Invalidate the attached textures for which the mask is True
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False))
with Pre => Object /= Subject and
(Mask.Color or Mask.Depth or Mask.Stencil) and
(if Object.Samples > 0 and Subject.Samples > 0 then
Object.Samples = Subject.Samples);
-- Copy one or more buffers, resolving multiple samples and scaling
-- if necessary, from the source to the destination framebuffer
--
-- If a buffer is specified in the mask, then the buffer should exist
-- in both framebuffers, otherwise the buffer is not copied. Call
-- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read
-- from and which buffers are written to.
--
-- Format of color buffers may differ and will be converted (if
-- supported). Formats of depth and stencil buffers must match.
--
-- Note: simultaneously resolving multiple samples and scaling
-- requires GL_EXT_framebuffer_multisample_blit_scaled.
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0)
with Pre => (not Object.Default and Texture.Allocated and
(if Attachment in Color_Attachment_Point then
(Object.Width = Texture.Width (Level) and
Object.Height = Texture.Height (Level))))
or else raise Constraint_Error with
"Cannot attach " & Rendering.Textures.Image (Texture, Level) &
" to " & Object.Image,
Post => Object.Has_Attachment (Attachment);
-- Attach the texture to the attachment point
--
-- The internal format of the texture must be valid for the given
-- attachment point.
--
-- If one of the attached textures is layered (3D, 1D/2D array, cube
-- map [array], or 2D multisampled array), then all attachments must
-- have the same kind.
--
-- All attachments of the framebuffer must have the same amount of
-- samples and they must all have fixed sample locations, or none of
-- them must have them.
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0);
-- Attach the texture to an attachment point based on the internal
-- format of the texture
--
-- Internally calls the procedure Attach above.
--
-- If the texture is color renderable, it will always be attached to
-- Color_Attachment_0. If you need to attach a texture to a different
-- color attachment point then use the other procedure Attach directly.
--
-- If the texture is layered and you want to attach a specific layer,
-- then you must call the procedure Attach_Layer below instead.
procedure Attach_Layer
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Layer : Natural;
Level : Textures.Mipmap_Level := 0)
with Pre => (not Object.Default and Texture.Allocated and
Texture.Layered and
(if Attachment in Color_Attachment_Point then
(Object.Width = Texture.Width (Level) and
Object.Height = Texture.Height (Level))))
or else raise Constraint_Error with
"Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) &
" to " & Object.Image,
Post => Object.Has_Attachment (Attachment);
-- Attach the selected 1D/2D layer of the texture to the attachment point
--
-- The internal format of the texture must be valid for the given
-- attachment point.
--
-- The texture must be layered (3D, 1D/2D array, cube
-- map [array], or 2D multisampled array).
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point)
with Pre => not Object.Default,
Post => not Object.Has_Attachment (Attachment);
-- Detach any texture currently attached to the given attachment point
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean;
Framebuffer_Incomplete_Error : exception;
private
package Attachment_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => Textures.Texture, "=" => Textures."=");
package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."=");
type Attachment_Array is array (FB.Attachment_Point)
of Attachment_Holder.Holder;
type Framebuffer (Default : Boolean) is tagged record
GL_Framebuffer : FB.Framebuffer;
Attachments : Attachment_Array;
Defaults : Buffer_Values;
Draw_Buffers : Color_Buffer_List_Holder.Holder;
Width, Height, Samples : Size;
end record;
end Orka.Rendering.Framebuffers;
|
Remove aspect Type_Invariant because of multisampled framebuffers
|
orka: Remove aspect Type_Invariant because of multisampled framebuffers
On-screen EGL window surfaces can be created using an EGL config that
requires a multisample buffer.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
e086c8c5f6dd65c3dfc499ac38a1bd674434d325
|
ARM/Nordic/drivers/nrf51-gpio.adb
|
ARM/Nordic/drivers/nrf51-gpio.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.GPIO; use NRF51_SVD.GPIO;
package body nRF51.GPIO is
---------
-- Set --
---------
overriding function Set
(This : GPIO_Point)
return Boolean
is
begin
return GPIO_Periph.OUT_k.Arr (This.Pin) = High;
end Set;
---------
-- Set --
---------
overriding procedure Set
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := High;
end Set;
-----------
-- Clear --
-----------
overriding procedure Clear
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := Low;
end Clear;
------------
-- Toggle --
------------
overriding procedure Toggle
(This : in out GPIO_Point)
is
begin
if This.Set then
This.Clear;
else
This.Set;
end if;
end Toggle;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(This : GPIO_Point;
Config : GPIO_Configuration)
is
CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin);
begin
CNF.DIR := (case Config.Mode is
when Mode_In => Input,
when Mode_Out => Output);
CNF.INPUT := (case Config.Input_Buffer is
when Input_Buffer_Connect => Connect,
when Input_Buffer_Disconnect => Disconnect);
CNF.PULL := (case Config.Resistors is
when No_Pull => Disabled,
when Pull_Up => Pullup,
when Pull_Down => Pulldown);
CNF.DRIVE := (case Config.Drive is
when Drive_S0S1 => S0S1,
when Drive_H0S1 => H0S1,
when Drive_S0H1 => S0H1,
when Drive_H0H1 => H0H1,
when Drive_D0S1 => D0S1,
when Drive_D0H1 => D0H1,
when Drive_S0D1 => S0D1,
when Drive_H0D1 => H0D1);
CNF.SENSE := (case Config.Sense is
when Sense_Disabled => Disabled,
when Sense_For_High_Level => High,
when Sense_For_Low_Level => Low);
end Configure_IO;
end nRF51.GPIO;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.GPIO; use NRF51_SVD.GPIO;
package body nRF51.GPIO is
---------
-- Set --
---------
overriding function Set
(This : GPIO_Point)
return Boolean
is
begin
return GPIO_Periph.IN_k.Arr (This.Pin) = High;
end Set;
---------
-- Set --
---------
overriding procedure Set
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := High;
end Set;
-----------
-- Clear --
-----------
overriding procedure Clear
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := Low;
end Clear;
------------
-- Toggle --
------------
overriding procedure Toggle
(This : in out GPIO_Point)
is
begin
if This.Set then
This.Clear;
else
This.Set;
end if;
end Toggle;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(This : GPIO_Point;
Config : GPIO_Configuration)
is
CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin);
begin
CNF.DIR := (case Config.Mode is
when Mode_In => Input,
when Mode_Out => Output);
CNF.INPUT := (case Config.Input_Buffer is
when Input_Buffer_Connect => Connect,
when Input_Buffer_Disconnect => Disconnect);
CNF.PULL := (case Config.Resistors is
when No_Pull => Disabled,
when Pull_Up => Pullup,
when Pull_Down => Pulldown);
CNF.DRIVE := (case Config.Drive is
when Drive_S0S1 => S0S1,
when Drive_H0S1 => H0S1,
when Drive_S0H1 => S0H1,
when Drive_H0H1 => H0H1,
when Drive_D0S1 => D0S1,
when Drive_D0H1 => D0H1,
when Drive_S0D1 => S0D1,
when Drive_H0D1 => H0D1);
CNF.SENSE := (case Config.Sense is
when Sense_Disabled => Disabled,
when Sense_For_High_Level => High,
when Sense_For_Low_Level => Low);
end Configure_IO;
end nRF51.GPIO;
|
Fix typo in GPIO
|
nRF51: Fix typo in GPIO
|
Ada
|
bsd-3-clause
|
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library
|
1f6d52ff21254e1c166cfefc965b89ed3b837685
|
matp/src/events/mat-events-targets.ads
|
matp/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Next_Id : Event_Id_Type := 0;
Prev_Id : Event_Id_Type := 0;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
Add the Next_Id and Prev_Id in the Probe_Event_Type record
|
Add the Next_Id and Prev_Id in the Probe_Event_Type record
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
83fc5b1934e0658119a00265cc8d58bd740d3dd6
|
src/gen-artifacts.ads
|
src/gen-artifacts.ads
|
-----------------------------------------------------------------------
-- gen-artifacts -- Artifacts for Code Generator
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with DOM.Core;
with Gen.Model;
with Gen.Model.Packages;
with Gen.Model.Projects;
-- The <b>Gen.Artifacts</b> package represents the methods and process to prepare,
-- control and realize the code generation.
package Gen.Artifacts is
type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE);
type Generator is limited interface;
-- Report an error and set the exit status accordingly
procedure Error (Handler : in out Generator;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "") is abstract;
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (Handler : in out Generator;
Name : in String;
Mode : in Iteration_Mode) is abstract;
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (Handler : in Generator;
Process : not null access
procedure (Dir : in String)) is abstract;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Artifact is abstract new Ada.Finalization.Limited_Controlled with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is null;
-- After the generation, perform a finalization step for the generation process.
procedure Finish (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Project : in out Gen.Model.Projects.Project_Definition'Class;
Context : in out Generator'Class) is null;
-- Check whether this artifact has been initialized.
function Is_Initialized (Handler : in Artifact) return Boolean;
private
type Artifact is abstract new Ada.Finalization.Limited_Controlled with record
Initialized : Boolean := False;
end record;
end Gen.Artifacts;
|
-----------------------------------------------------------------------
-- gen-artifacts -- Artifacts for Code Generator
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with DOM.Core;
with Gen.Model;
with Gen.Model.Packages;
with Gen.Model.Projects;
-- The <b>Gen.Artifacts</b> package represents the methods and process to prepare,
-- control and realize the code generation.
package Gen.Artifacts is
type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE);
type Generator is limited interface;
-- Report an error and set the exit status accordingly
procedure Error (Handler : in out Generator;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "") is abstract;
-- Get the result directory path.
function Get_Result_Directory (Handler : in Generator) return String is abstract;
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (Handler : in out Generator;
Name : in String;
Mode : in Iteration_Mode) is abstract;
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (Handler : in Generator;
Process : not null access
procedure (Dir : in String)) is abstract;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Artifact is abstract new Ada.Finalization.Limited_Controlled with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is null;
-- After the generation, perform a finalization step for the generation process.
procedure Finish (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Project : in out Gen.Model.Projects.Project_Definition'Class;
Context : in out Generator'Class) is null;
-- Check whether this artifact has been initialized.
function Is_Initialized (Handler : in Artifact) return Boolean;
private
type Artifact is abstract new Ada.Finalization.Limited_Controlled with record
Initialized : Boolean := False;
end record;
end Gen.Artifacts;
|
Add the Get_Result_Directory function to the Artifact interface
|
Add the Get_Result_Directory function to the Artifact interface
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
0079384afb8295d6a0e71bd8979db943d5ea1d72
|
src/gen-commands-templates.adb
|
src/gen-commands-templates.adb
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- 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.IO_Exceptions;
with Ada.Directories;
with GNAT.Command_Line;
with Gen.Artifacts;
with Util.Log.Loggers;
with Util.Files;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
package body Gen.Commands.Templates is
use Ada.Strings.Unbounded;
use Util.Log;
use GNAT.Command_Line;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates");
-- ------------------------------
-- Page Creation Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
function Get_Output_Dir return String;
function Get_Output_Dir return String is
Dir : constant String := Generator.Get_Result_Directory;
begin
if Length (Cmd.Base_Dir) = 0 then
return Dir;
else
return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir));
end if;
end Get_Output_Dir;
Out_Dir : constant String := Get_Output_Dir;
Iter : Param_Vectors.Cursor := Cmd.Params.First;
begin
Generator.Read_Project ("dynamo.xml", False);
while Param_Vectors.Has_Element (Iter) loop
declare
P : constant Param := Param_Vectors.Element (Iter);
Value : constant String := Get_Argument;
begin
if not P.Is_Optional and Value'Length = 0 then
Generator.Error ("Missing argument for {0}", To_String (P.Argument));
return;
end if;
Generator.Set_Global (To_String (P.Name), Value);
end;
Param_Vectors.Next (Iter);
end loop;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (To_Unbounded_String (Out_Dir));
declare
Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First;
begin
while Util.Strings.Sets.Has_Element (Iter) loop
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
Util.Strings.Sets.Element (Iter));
Util.Strings.Sets.Next (Iter);
end loop;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Generator);
use Ada.Text_IO;
begin
Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title));
Put_Line ("Usage: " & To_String (Cmd.Usage));
New_Line;
Put_Line (To_String (Cmd.Help_Msg));
end Help;
type Command_Fields is (FIELD_NAME,
FIELD_HELP,
FIELD_USAGE,
FIELD_TITLE,
FIELD_BASEDIR,
FIELD_PARAM,
FIELD_PARAM_NAME,
FIELD_PARAM_OPTIONAL,
FIELD_PARAM_ARG,
FIELD_TEMPLATE,
FIELD_COMMAND);
type Command_Loader is record
Command : Command_Access := null;
P : Param;
end record;
type Command_Loader_Access is access all Command_Loader;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object);
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String;
-- ------------------------------
-- Convert the object value into a string and trim any space/tab/newlines.
-- ------------------------------
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is
Result : constant String := Util.Beans.Objects.To_String (Value);
First_Pos : Natural := Result'First;
Last_Pos : Natural := Result'Last;
C : Character;
begin
while First_Pos <= Last_Pos loop
C := Result (First_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
First_Pos := First_Pos + 1;
end loop;
while Last_Pos >= First_Pos loop
C := Result (Last_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
Last_Pos := Last_Pos - 1;
end loop;
return To_Unbounded_String (Result (First_Pos .. Last_Pos));
end To_String;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
if Field = FIELD_COMMAND then
if Closure.Command /= null then
Log.Info ("Adding command {0}", Closure.Command.Name);
Add_Command (Name => To_String (Closure.Command.Name),
Cmd => Closure.Command.all'Access);
Closure.Command := null;
end if;
else
if Closure.Command = null then
Closure.Command := new Gen.Commands.Templates.Command;
end if;
case Field is
when FIELD_NAME =>
Closure.Command.Name := To_String (Value);
when FIELD_TITLE =>
Closure.Command.Title := To_String (Value);
when FIELD_USAGE =>
Closure.Command.Usage := To_String (Value);
when FIELD_HELP =>
Closure.Command.Help_Msg := To_String (Value);
when FIELD_TEMPLATE =>
Closure.Command.Templates.Include (To_String (Value));
when FIELD_PARAM_NAME =>
Closure.P.Name := To_Unbounded_String (Value);
when FIELD_PARAM_OPTIONAL =>
Closure.P.Is_Optional := To_Boolean (Value);
when FIELD_PARAM_ARG =>
Closure.P.Argument := To_Unbounded_String (Value);
when FIELD_PARAM =>
Closure.P.Value := To_Unbounded_String (Value);
Closure.Command.Params.Append (Closure.P);
Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Is_Optional := False;
when FIELD_BASEDIR =>
Closure.Command.Base_Dir := To_Unbounded_String (Value);
when FIELD_COMMAND =>
null;
when others =>
null;
end case;
end if;
end Set_Member;
package Command_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader,
Element_Type_Access => Command_Loader_Access,
Fields => Command_Fields,
Set_Member => Set_Member);
Cmd_Mapper : aliased Command_Mapper.Mapper;
-- ------------------------------
-- Read the template commands defined in dynamo configuration directory.
-- ------------------------------
procedure Read_Commands (Generator : in out Gen.Generator.Handler) is
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Read the XML command file.
-- ------------------------------
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
Loader : aliased Command_Loader;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading command file '{0}'", File_Path);
Done := False;
-- Create the mapping to load the XML command file.
Reader.Add_Mapping ("commands", Cmd_Mapper'Access);
-- Set the context for Set_Member.
Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access);
-- Read the XML command file.
Reader.Parse (File_Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Generator.Error ("Command file {0} does not exist", File_Path);
end Read_Command;
Config_Dir : constant String := Generator.Get_Config_Directory;
Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir");
Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir);
begin
if Ada.Directories.Exists (Path) then
Util.Files.Iterate_Files_Path (Path => Path,
Pattern => "*.xml",
Process => Read_Command'Access);
end if;
end Read_Commands;
begin
-- Setup the mapper to load XML commands.
Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME);
Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE);
Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE);
Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP);
Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR);
Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM);
Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME);
Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL);
Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG);
Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND);
end Gen.Commands.Templates;
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- 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.IO_Exceptions;
with Ada.Directories;
with GNAT.Command_Line;
with Gen.Artifacts;
with Util.Log.Loggers;
with Util.Files;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
package body Gen.Commands.Templates is
use Ada.Strings.Unbounded;
use Util.Log;
use GNAT.Command_Line;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates");
-- ------------------------------
-- Page Creation Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
function Get_Output_Dir return String;
function Get_Output_Dir return String is
Dir : constant String := Generator.Get_Result_Directory;
begin
if Length (Cmd.Base_Dir) = 0 then
return Dir;
else
return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir));
end if;
end Get_Output_Dir;
Out_Dir : constant String := Get_Output_Dir;
Iter : Param_Vectors.Cursor := Cmd.Params.First;
begin
Generator.Read_Project ("dynamo.xml", False);
while Param_Vectors.Has_Element (Iter) loop
declare
P : constant Param := Param_Vectors.Element (Iter);
Value : constant String := Get_Argument;
begin
if not P.Is_Optional and Value'Length = 0 then
Generator.Error ("Missing argument for {0}", To_String (P.Argument));
return;
end if;
Generator.Set_Global (To_String (P.Name), Value);
end;
Param_Vectors.Next (Iter);
end loop;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (To_Unbounded_String (Out_Dir));
declare
Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First;
begin
while Util.Strings.Sets.Has_Element (Iter) loop
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
Util.Strings.Sets.Element (Iter));
Util.Strings.Sets.Next (Iter);
end loop;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Generator);
use Ada.Text_IO;
begin
Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title));
Put_Line ("Usage: " & To_String (Cmd.Usage));
New_Line;
Put_Line (To_String (Cmd.Help_Msg));
end Help;
type Command_Fields is (FIELD_NAME,
FIELD_HELP,
FIELD_USAGE,
FIELD_TITLE,
FIELD_BASEDIR,
FIELD_PARAM,
FIELD_PARAM_NAME,
FIELD_PARAM_OPTIONAL,
FIELD_PARAM_ARG,
FIELD_TEMPLATE,
FIELD_COMMAND);
type Command_Loader is record
Command : Command_Access := null;
P : Param;
end record;
type Command_Loader_Access is access all Command_Loader;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object);
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String;
-- ------------------------------
-- Convert the object value into a string and trim any space/tab/newlines.
-- ------------------------------
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is
Result : constant String := Util.Beans.Objects.To_String (Value);
First_Pos : Natural := Result'First;
Last_Pos : Natural := Result'Last;
C : Character;
begin
while First_Pos <= Last_Pos loop
C := Result (First_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
First_Pos := First_Pos + 1;
end loop;
while Last_Pos >= First_Pos loop
C := Result (Last_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
Last_Pos := Last_Pos - 1;
end loop;
return To_Unbounded_String (Result (First_Pos .. Last_Pos));
end To_String;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
if Field = FIELD_COMMAND then
if Closure.Command /= null then
Log.Info ("Adding command {0}", Closure.Command.Name);
Add_Command (Name => To_String (Closure.Command.Name),
Cmd => Closure.Command.all'Access);
Closure.Command := null;
end if;
else
if Closure.Command = null then
Closure.Command := new Gen.Commands.Templates.Command;
end if;
case Field is
when FIELD_NAME =>
Closure.Command.Name := To_String (Value);
when FIELD_TITLE =>
Closure.Command.Title := To_String (Value);
when FIELD_USAGE =>
Closure.Command.Usage := To_String (Value);
when FIELD_HELP =>
Closure.Command.Help_Msg := To_String (Value);
when FIELD_TEMPLATE =>
Closure.Command.Templates.Include (To_String (Value));
when FIELD_PARAM_NAME =>
Closure.P.Name := To_Unbounded_String (Value);
when FIELD_PARAM_OPTIONAL =>
Closure.P.Is_Optional := To_Boolean (Value);
when FIELD_PARAM_ARG =>
Closure.P.Argument := To_Unbounded_String (Value);
when FIELD_PARAM =>
Closure.P.Value := To_Unbounded_String (Value);
Closure.Command.Params.Append (Closure.P);
Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Is_Optional := False;
when FIELD_BASEDIR =>
Closure.Command.Base_Dir := To_Unbounded_String (Value);
when FIELD_COMMAND =>
null;
end case;
end if;
end Set_Member;
package Command_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader,
Element_Type_Access => Command_Loader_Access,
Fields => Command_Fields,
Set_Member => Set_Member);
Cmd_Mapper : aliased Command_Mapper.Mapper;
-- ------------------------------
-- Read the template commands defined in dynamo configuration directory.
-- ------------------------------
procedure Read_Commands (Generator : in out Gen.Generator.Handler) is
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Read the XML command file.
-- ------------------------------
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
Loader : aliased Command_Loader;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading command file '{0}'", File_Path);
Done := False;
-- Create the mapping to load the XML command file.
Reader.Add_Mapping ("commands", Cmd_Mapper'Access);
-- Set the context for Set_Member.
Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access);
-- Read the XML command file.
Reader.Parse (File_Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Generator.Error ("Command file {0} does not exist", File_Path);
end Read_Command;
Config_Dir : constant String := Generator.Get_Config_Directory;
Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir");
Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir);
begin
Log.Debug ("Checking commands in {0}", Path);
if Ada.Directories.Exists (Path) then
Util.Files.Iterate_Files_Path (Path => Path,
Pattern => "*.xml",
Process => Read_Command'Access);
end if;
end Read_Commands;
begin
-- Setup the mapper to load XML commands.
Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME);
Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE);
Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE);
Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP);
Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR);
Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM);
Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME);
Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL);
Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG);
Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND);
end Gen.Commands.Templates;
|
Add a log and fix compilation warning
|
Add a log and fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
e7885bb14fd33047bdcdc96333724b3e94770762
|
src/gen-artifacts-distribs-merges.ads
|
src/gen-artifacts-distribs-merges.ads
|
-----------------------------------------------------------------------
-- 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 EL.Variables.Default;
with EL.Contexts.Default;
with Util.Beans.Objects.Maps;
-- === Distribution: webmerge ===
-- The `webmerge` distribution rule is intended to merge Javascript or CSS files
-- which are used by XHTML presentation files. It requires some help from the
-- developer to describe what files must be merged. The XHTML file must contain
-- well defined XML comments which are used to identify the merging areas.
-- The CSS file merge start section begins with:
--
-- <!-- DYNAMO-MERGE-START link=#{contextPath}/css/target-merge-1.css -->
--
-- and the Javascript merge start begings with:
--
-- <!-- DYNAMO-MERGE-START script=#{contextPath}/js/target-merge-1.js -->
--
-- The merge section is terminated by the following XML comment:
--
-- <!-- DYNAMO-MERGE-END -->
--
-- Everything withing these XML comments is then replaced either by a `link`
-- HTML tag or by a `script` HTML tag and a file described either by the
-- `link=` or `script=` markers is generated to include every `link` or `script`
-- that was defined within the XML comment markers. For example, with the following
-- XHTML extract:
--
-- <!-- DYNAMO-MERGE-START link=#{contextPath}/css/merged.css -->
-- <link media="screen" type="text/css" rel="stylesheet" href="#{contextPath}/css/awa.css"/>
-- <link media="screen" type="text/css" rel="stylesheet" href="#{jquery.uiCssPath}"/>
-- <link media="screen" type="text/css" rel="stylesheet" href="#{jquery.chosenCssPath}"/>
-- <!-- DYNAMO-MERGE-END -->
--
-- The generated file `css/merged.css` will include `awa.css`, `jquery-ui-1.12.1.css`,
-- `chosen.css` and the XHTML will be replaced to include `css/merge.css` only
-- by using the following XHTML:
--
-- <link media='screen' type='text/css' rel='stylesheet' href='#{contextPath}/css/merged.css'/>
--
-- To use the `webmerge`, the `package.xml` description file should contain
-- the following command:
--
-- <install mode='merge' dir='web'>
-- <property name="contextPath"></property>
-- <property name="jquery.path">/js/jquery-3.4.1.js</property>
-- <property name="jquery.uiCssPath">/css/redmond/jquery-ui-1.12.1.css</property>
-- <property name="jquery.chosenCssPath">/css/jquery-chosen-1.8.7/chosen.css</property>
-- <property name="jquery.uiPath">/js/jquery-ui-1.12.1</property>
-- <fileset dir="web">
-- <include name="WEB-INF/layouts/*.xhtml"/>
-- </fileset>
-- </install>
--
private package Gen.Artifacts.Distribs.Merges is
-- Create a distribution rule to copy a set of files or directories.
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Merge_Rule is new Distrib_Rule with private;
type Merge_Rule_Access is access all Merge_Rule;
-- Get a name to qualify the installation rule (used for logs).
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class);
private
type Merge_Rule is new Distrib_Rule with record
Params : Util.Beans.Objects.Maps.Map_Bean;
Context : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
end record;
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 EL.Variables.Default;
with EL.Contexts.Default;
with Util.Strings.Maps;
with Util.Beans.Objects.Maps;
-- === Distribution: webmerge ===
-- The `webmerge` distribution rule is intended to merge Javascript or CSS files
-- which are used by XHTML presentation files. It requires some help from the
-- developer to describe what files must be merged. The XHTML file must contain
-- well defined XML comments which are used to identify the merging areas.
-- The CSS file merge start section begins with:
--
-- <!-- DYNAMO-MERGE-START link=#{contextPath}/css/target-merge-1.css -->
--
-- and the Javascript merge start begings with:
--
-- <!-- DYNAMO-MERGE-START script=#{contextPath}/js/target-merge-1.js -->
--
-- The merge section is terminated by the following XML comment:
--
-- <!-- DYNAMO-MERGE-END -->
--
-- Everything withing these XML comments is then replaced either by a `link`
-- HTML tag or by a `script` HTML tag and a file described either by the
-- `link=` or `script=` markers is generated to include every `link` or `script`
-- that was defined within the XML comment markers. For example, with the following
-- XHTML extract:
--
-- <!-- DYNAMO-MERGE-START link=#{contextPath}/css/merged.css -->
-- <link media="screen" type="text/css" rel="stylesheet" href="#{contextPath}/css/awa.css"/>
-- <link media="screen" type="text/css" rel="stylesheet" href="#{jquery.uiCssPath}"/>
-- <link media="screen" type="text/css" rel="stylesheet" href="#{jquery.chosenCssPath}"/>
-- <!-- DYNAMO-MERGE-END -->
--
-- The generated file `css/merged.css` will include `awa.css`, `jquery-ui-1.12.1.css`,
-- `chosen.css` and the XHTML will be replaced to include `css/merge.css` only
-- by using the following XHTML:
--
-- <link media='screen' type='text/css' rel='stylesheet' href='#{contextPath}/css/merged.css'/>
--
-- To use the `webmerge`, the `package.xml` description file should contain
-- the following command:
--
-- <install mode='merge' dir='web'>
-- <property name="contextPath"></property>
-- <property name="jquery.path">/js/jquery-3.4.1.js</property>
-- <property name="jquery.uiCssPath">/css/redmond/jquery-ui-1.12.1.css</property>
-- <property name="jquery.chosenCssPath">/css/jquery-chosen-1.8.7/chosen.css</property>
-- <property name="jquery.uiPath">/js/jquery-ui-1.12.1</property>
-- <fileset dir="web">
-- <include name="WEB-INF/layouts/*.xhtml"/>
-- </fileset>
-- </install>
--
private package Gen.Artifacts.Distribs.Merges is
-- Create a distribution rule to copy a set of files or directories.
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Merge_Rule is new Distrib_Rule with private;
type Merge_Rule_Access is access all Merge_Rule;
-- Get a name to qualify the installation rule (used for logs).
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class);
private
type Merge_Rule is new Distrib_Rule with record
Params : Util.Beans.Objects.Maps.Map_Bean;
Context : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Replace : Util.Strings.Maps.Map;
end record;
end Gen.Artifacts.Distribs.Merges;
|
Add Replace map to help some replacement patterns
|
Add Replace map to help some replacement patterns
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3b1d51572e7c242b3fdb58d2312eb2af4e6f5026
|
matp/src/frames/mat-frames-targets.ads
|
matp/src/frames/mat-frames-targets.ads
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- 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.Finalization;
package MAT.Frames.Targets is
type Target_Frames is tagged limited private;
type Target_Frames_Access is access all Target_Frames'Class;
-- 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 out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Get the number of different stack frames which have been registered.
function Get_Frame_Count (Frame : in Target_Frames) return Natural;
private
protected type Frames_Type is
-- 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 (Pc : in Frame_Table;
Result : out Frame_Type);
-- Clear and destroy all the frame instances.
procedure Clear;
private
Root : Frame_Type := Create_Root;
end Frames_Type;
type Target_Frames is new Ada.Finalization.Limited_Controlled with record
Frames : Frames_Type;
end record;
-- Release all the stack frames.
overriding
procedure Finalize (Frames : in out Target_Frames);
end MAT.Frames.Targets;
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- 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.Finalization;
package MAT.Frames.Targets is
type Target_Frames is tagged limited private;
type Target_Frames_Access is access all Target_Frames'Class;
-- 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 out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Get the number of different stack frames which have been registered.
function Get_Frame_Count (Frame : in Target_Frames) return Natural;
private
protected type Frames_Type is
-- Get the number of different stack frames which have been registered.
function Get_Frame_Count return Natural;
-- 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 (Pc : in Frame_Table;
Result : out Frame_Type);
-- Clear and destroy all the frame instances.
procedure Clear;
private
Root : Frame_Type := Create_Root;
end Frames_Type;
type Target_Frames is new Ada.Finalization.Limited_Controlled with record
Frames : Frames_Type;
end record;
-- Release all the stack frames.
overriding
procedure Finalize (Frames : in out Target_Frames);
end MAT.Frames.Targets;
|
Declare the Get_Frame_Count protected function
|
Declare the Get_Frame_Count protected function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ae8256bc3d83a2153a6e47c52de5c5d9188cad1e
|
regtests/asf-contexts-faces-tests.adb
|
regtests/asf-contexts-faces-tests.adb
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Util.Test_Caller;
package body ASF.Contexts.Faces.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Contexts.Faces");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message",
Test_Add_Message'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity",
Test_Max_Severity'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message",
Test_Get_Messages'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception",
Test_Queue_Exception'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash",
Test_Flash_Context'Access);
end Add_Tests;
-- Test the faces message queue.
procedure Test_Add_Message (T : in out Test) is
Ctx : Faces_Context;
begin
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg2");
Ctx.Add_Message (Client_Id => "", Message => "msg3");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN);
Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR);
Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed");
end Test_Add_Message;
procedure Test_Max_Severity (T : in out Test) is
Ctx : Faces_Context;
begin
T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN);
T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message");
end Test_Max_Severity;
procedure Test_Get_Messages (T : in out Test) is
Ctx : Faces_Context;
begin
-- Iterator on an empty message list.
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "");
begin
T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message");
end;
Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO);
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info");
M : Message;
begin
T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message");
M := Vectors.Element (Iter);
Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message");
Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details");
T.Assert (INFO = Get_Severity (M), "Invalid severity");
end;
end Test_Get_Messages;
-- ------------------------------
-- Test adding some exception in the faces context.
-- ------------------------------
procedure Test_Queue_Exception (T : in out Test) is
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural);
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class);
Ctx : Faces_Context;
Cnt : Natural := 0;
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural) is
begin
if Depth > 0 then
Raise_Exception (Depth - 1, Excep);
end if;
case Excep is
when 1 =>
raise Constraint_Error with "except code 1";
when 2 =>
raise Ada.IO_Exceptions.Name_Error;
when others =>
raise Program_Error with "Testing program error";
end case;
end Raise_Exception;
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Context, Event);
begin
Cnt := Cnt + 1;
Remove := False;
end Check_Exception;
begin
-- Create some exceptions and queue them.
for I in 1 .. 3 loop
begin
Raise_Exception (3, I);
exception
when E : others =>
Ctx.Queue_Exception (E);
end;
end loop;
Ctx.Iterate_Exception (Check_Exception'Access);
Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued");
end Test_Queue_Exception;
-- ------------------------------
-- Test the flash instance.
-- ------------------------------
procedure Test_Flash_Context (T : in out Test) is
use type ASF.Contexts.Faces.Flash_Context_Access;
Ctx : Faces_Context;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
T.Assert (Flash /= null, "Null flash context returned");
end Test_Flash_Context;
end ASF.Contexts.Faces.Tests;
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Util.Test_Caller;
with ASF.Contexts.Flash;
package body ASF.Contexts.Faces.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Contexts.Faces");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message",
Test_Add_Message'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity",
Test_Max_Severity'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message",
Test_Get_Messages'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception",
Test_Queue_Exception'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash",
Test_Flash_Context'Access);
end Add_Tests;
-- Test the faces message queue.
procedure Test_Add_Message (T : in out Test) is
Ctx : Faces_Context;
begin
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg2");
Ctx.Add_Message (Client_Id => "", Message => "msg3");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN);
Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR);
Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed");
end Test_Add_Message;
procedure Test_Max_Severity (T : in out Test) is
Ctx : Faces_Context;
begin
T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN);
T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message");
end Test_Max_Severity;
procedure Test_Get_Messages (T : in out Test) is
Ctx : Faces_Context;
begin
-- Iterator on an empty message list.
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "");
begin
T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message");
end;
Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO);
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info");
M : Message;
begin
T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message");
M := Vectors.Element (Iter);
Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message");
Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details");
T.Assert (INFO = Get_Severity (M), "Invalid severity");
end;
end Test_Get_Messages;
-- ------------------------------
-- Test adding some exception in the faces context.
-- ------------------------------
procedure Test_Queue_Exception (T : in out Test) is
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural);
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class);
Ctx : Faces_Context;
Cnt : Natural := 0;
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural) is
begin
if Depth > 0 then
Raise_Exception (Depth - 1, Excep);
end if;
case Excep is
when 1 =>
raise Constraint_Error with "except code 1";
when 2 =>
raise Ada.IO_Exceptions.Name_Error;
when others =>
raise Program_Error with "Testing program error";
end case;
end Raise_Exception;
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Context, Event);
begin
Cnt := Cnt + 1;
Remove := False;
end Check_Exception;
begin
-- Create some exceptions and queue them.
for I in 1 .. 3 loop
begin
Raise_Exception (3, I);
exception
when E : others =>
Ctx.Queue_Exception (E);
end;
end loop;
Ctx.Iterate_Exception (Check_Exception'Access);
Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued");
end Test_Queue_Exception;
-- ------------------------------
-- Test the flash instance.
-- ------------------------------
procedure Test_Flash_Context (T : in out Test) is
use type ASF.Contexts.Faces.Flash_Context_Access;
Ctx : Faces_Context;
Flash : aliased ASF.Contexts.Flash.Flash_Context;
begin
Ctx.Set_Flash (Flash'Unchecked_Access);
T.Assert (Ctx.Get_Flash /= null, "Null flash context returned");
end Test_Flash_Context;
end ASF.Contexts.Faces.Tests;
|
Fix flash unit test
|
Fix flash unit test
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
74b9364068f8bd9c0f601a5f36d15376aedd5f36
|
regtests/wiki-tests.adb
|
regtests/wiki-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Plugins.Templates;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML then
declare
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name));
end;
elsif T.Is_Html then
declare
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render HTML " & To_String (T.Name));
end;
else
declare
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Text " & To_String (T.Name));
end;
end if;
end;
Input.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Plugins.Templates;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML then
declare
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name));
end;
elsif T.Is_Html then
declare
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render HTML " & To_String (T.Name));
end;
else
declare
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Text " & To_String (T.Name));
end;
end if;
end;
Input.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a000d90f39cd5da1a3847e25a45fa3a4b5b79e21
|
awa/plugins/awa-mail/src/awa-mail-clients-files.ads
|
awa/plugins/awa-mail/src/awa-mail-clients-files.ads
|
-----------------------------------------------------------------------
-- awa-mail-clients-files -- Mail client dump/file implementation
-- Copyright (C) 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
with Util.Concurrent.Counters;
-- The <b>AWA.Mail.Clients.Files</b> package provides a dump implementation of the
-- mail client interfaces on top of raw system files.
package AWA.Mail.Clients.Files is
NAME : constant String := "file";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>File_Mail_Message</b> represents a mail message that is written on a file in
-- in specific directory.
type File_Mail_Message is new Mail_Message with private;
type File_Mail_Message_Access is access all File_Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
overriding
procedure Set_From (Message : in out File_Mail_Message;
Name : in String;
Address : in String);
-- Add a recipient for the message.
overriding
procedure Add_Recipient (Message : in out File_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out File_Mail_Message;
Subject : in String);
-- Set the body of the message.
overriding
procedure Set_Body (Message : in out File_Mail_Message;
Content : in String);
-- Send the email message.
overriding
procedure Send (Message : in out File_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type File_Mail_Manager is limited new Mail_Manager with private;
type File_Mail_Manager_Access is access all File_Mail_Manager'Class;
-- Create a file based mail manager and configure it according to the properties.
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access;
-- Create a new mail message.
overriding
function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access;
private
type File_Mail_Message is new Mail_Message with record
Manager : File_Mail_Manager_Access;
From : Ada.Strings.Unbounded.Unbounded_String;
To : Ada.Strings.Unbounded.Unbounded_String;
Cc : Ada.Strings.Unbounded.Unbounded_String;
Bcc : Ada.Strings.Unbounded.Unbounded_String;
Subject : Ada.Strings.Unbounded.Unbounded_String;
Message : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Mail_Manager is limited new Mail_Manager with record
Self : File_Mail_Manager_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Index : Util.Concurrent.Counters.Counter;
end record;
end AWA.Mail.Clients.Files;
|
-----------------------------------------------------------------------
-- awa-mail-clients-files -- Mail client dump/file implementation
-- Copyright (C) 2012, 2014, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
with Util.Concurrent.Counters;
-- The <b>AWA.Mail.Clients.Files</b> package provides a dump implementation of the
-- mail client interfaces on top of raw system files.
package AWA.Mail.Clients.Files is
NAME : constant String := "file";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>File_Mail_Message</b> represents a mail message that is written on a file in
-- in specific directory.
type File_Mail_Message is new Mail_Message with private;
type File_Mail_Message_Access is access all File_Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
overriding
procedure Set_From (Message : in out File_Mail_Message;
Name : in String;
Address : in String);
-- Add a recipient for the message.
overriding
procedure Add_Recipient (Message : in out File_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out File_Mail_Message;
Subject : in String);
-- Set the body of the message.
overriding
procedure Set_Body (Message : in out File_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String);
-- Add an attachment with the given content.
overriding
procedure Add_Attachment (Message : in out File_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String);
-- Send the email message.
overriding
procedure Send (Message : in out File_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type File_Mail_Manager is limited new Mail_Manager with private;
type File_Mail_Manager_Access is access all File_Mail_Manager'Class;
-- Create a file based mail manager and configure it according to the properties.
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access;
-- Create a new mail message.
overriding
function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access;
private
type File_Mail_Message is new Mail_Message with record
Manager : File_Mail_Manager_Access;
From : Ada.Strings.Unbounded.Unbounded_String;
To : Ada.Strings.Unbounded.Unbounded_String;
Cc : Ada.Strings.Unbounded.Unbounded_String;
Bcc : Ada.Strings.Unbounded.Unbounded_String;
Subject : Ada.Strings.Unbounded.Unbounded_String;
Message : Ada.Strings.Unbounded.Unbounded_String;
Html : Ada.Strings.Unbounded.Unbounded_String;
Attachments : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Mail_Manager is limited new Mail_Manager with record
Self : File_Mail_Manager_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Index : Util.Concurrent.Counters.Counter;
end record;
end AWA.Mail.Clients.Files;
|
Add Add_Attachment procedure and update Set_Body to handle multipart alternatives
|
Add Add_Attachment procedure and update Set_Body to handle multipart alternatives
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f21c7d0d0ef0134eec59989d053c3ab8f82a07f5
|
src/asf-sessions-factory.ads
|
src/asf-sessions-factory.ads
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package ASF.Sessions.Factory is
type Session_Factory is new Ada.Finalization.Limited_Controlled with private;
-- Create a new session
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session);
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access);
-- Deletes the session.
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session);
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session);
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration;
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration);
private
use Util.Strings;
package Session_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Name_Access,
Element_Type => Session,
Hash => Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
protected type Session_Cache is
-- Find the session in the session cache.
function Find (Id : in String) return Session;
-- Insert the session in the session cache.
procedure Insert (Sess : in Session);
-- Generate a random bitstream.
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array);
-- Initialize the random generator.
procedure Initialize;
private
-- Id to session map.
Sessions : Session_Maps.Map;
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
end Session_Cache;
type Session_Factory is new Ada.Finalization.Limited_Controlled with record
-- The session cache.
Sessions : Session_Cache;
-- Max inactive time in seconds.
Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT;
-- Number of 32-bit random numbers used for the ID generation.
Id_Size : Ada.Streams.Stream_Element_Offset := 8;
end record;
-- Initialize the session factory.
overriding
procedure Initialize (Factory : in out Session_Factory);
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2014, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package ASF.Sessions.Factory is
type Session_Factory is new Ada.Finalization.Limited_Controlled with private;
-- Create a new session
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session);
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access);
-- Deletes the session.
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session);
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session);
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration;
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration);
private
use Util.Strings;
package Session_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Name_Access,
Element_Type => Session,
Hash => Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
protected type Session_Cache is
-- Find the session in the session cache.
function Find (Id : in String) return Session;
-- Insert the session in the session cache.
procedure Insert (Sess : in Session);
-- Remove the session from the session cache.
procedure Delete (Sess : in out Session);
-- Generate a random bitstream.
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array);
-- Initialize the random generator.
procedure Initialize;
private
-- Id to session map.
Sessions : Session_Maps.Map;
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
end Session_Cache;
type Session_Factory is new Ada.Finalization.Limited_Controlled with record
-- The session cache.
Sessions : Session_Cache;
-- Max inactive time in seconds.
Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT;
-- Number of 32-bit random numbers used for the ID generation.
Id_Size : Ada.Streams.Stream_Element_Offset := 8;
end record;
-- Initialize the session factory.
overriding
procedure Initialize (Factory : in out Session_Factory);
end ASF.Sessions.Factory;
|
Declare the Delete protected procedure
|
Declare the Delete protected procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
12c5deff1d87701565c08fb718883fd96facbebb
|
src/lumen-window.ads
|
src/lumen-window.ads
|
-- Lumen.Window -- Create and destroy native windows and associated OpenGL
-- rendering contexts
--
-- Chip Richards, NiEstu, Phoenix AZ, Spring 2010
-- This code is covered by the ISC License:
--
-- Copyright (c) 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Lumen.Internal;
package Lumen.Window is
-- Handle for a Lumen window
subtype Handle is Internal.Window_Info;
-- Handle for an OpenGL rendering context
subtype Context_Handle is Internal.GLX_Context;
-- Null window; in X, this means the root window is the parent
No_Window : constant Handle := (Display => Internal.Null_Display_Pointer,
Window => 0,
Visual => null,
Context => Internal.Null_Context);
-- Means "no GL context"; for Create, means create a new one
No_Context : constant Context_Handle := Internal.Null_Context;
-- Types of events wanted, and a set listing them.
type Wanted_Event is (Want_Key_Press, Want_Key_Release, Want_Button_Press, Want_Button_Release,
Want_Window_Enter, Want_Window_Leave,
Want_Pointer_Move, Want_Pointer_Drag,
Want_Exposure, Want_Resize, Want_Focus_Change);
type Wanted_Event_Set is array (Wanted_Event) of Boolean;
Want_No_Events : Wanted_Event_Set := (others => False);
Want_All_Events : Wanted_Event_Set := (others => True);
-- Rendering context's color depth
type Color_Depth is (Pseudo_Color, True_Color);
-- Local exceptions raised by these procedures
Connection_Failed : exception; -- can't connect to X server
Context_Failed : exception; -- can't create or attach OpenGL context
-- Create a native window, with defaults for configuration intended to
-- create a "usable" window. Details about the parameters are:
--
-- Parent: Handle of an existing window that will act as the new window's
-- parent, or No_Window, meaning an independent top-level window.
--
-- Width, Height: Window dimensions in pixels.
--
-- Events: Set of events this window wishes to receive.
--
-- Name: Name associated with new window, often displayed in the window's
-- title bar. If blank, the executable's filename is used.
--
-- Icon_Name: Name associated with the window's icon. If blank, the
-- executable's filename is used.
--
-- Class_Name, Instance_Name: Together these make up the window's "class".
-- If blank, the class name is set to the executable's filename with
-- initial capitalization; the instance name is set to the executable's
-- filename.
--
-- Context: An existing GL rendering context to be used in the new window,
-- or No_Context, meaning a new context is created for the window.
--
-- Depth: The color depth of the GL rendering context, either true-color or
-- indexed/pseudo-color.
--
-- Animated: Whether the GL rendering context will be double-buffered, thus
-- allowing smooth animation.
function Create (Parent : Handle := No_Window;
Width : Natural := 400;
Height : Natural := 400;
Events : Wanted_Event_Set := Want_No_Events;
Name : String := "";
Icon_Name : String := "";
Class_Name : String := "";
Instance_Name : String := "";
Context : Context_Handle := No_Context;
Depth : Color_Depth := True_Color;
Animated : Boolean := True)
return Handle;
-- Destroy a native window, including its current rendering context.
procedure Destroy (Win : in out Handle);
-- Set various textual names associated with a window. Null string means
-- leave the current value unchanged;
procedure Set_Names (Win : in Handle;
Name : in String := "";
Icon_Name : in String := "";
Class_Name : in String := "";
Instance_Name : in String := "");
-- Create an OpenGL rendering context; needed only when you want a second
-- or subsequent context for a window, since Create makes one to start
-- with
function Create_Context (Win : Handle) return Context_Handle;
-- Destroy a window's OpenGL rendering context; should be followed either
-- by a Make_Current or a Destroy_Window
procedure Destroy_Context (Win : in out Handle);
-- Make a rendering context the current one for a window
procedure Make_Current (Win : in out Handle;
Context : in Context_Handle);
-- Promotes the back buffer to front; only valid if the window is double
-- buffered, meaning Animated was true when the window was created. Useful
-- for smooth animation.
procedure Swap (Win : in Handle);
private
pragma Linker_Options ("-lX11");
pragma Linker_Options ("-lGL");
end Lumen.Window;
|
-- Lumen.Window -- Create and destroy native windows and associated OpenGL
-- rendering contexts
--
-- Chip Richards, NiEstu, Phoenix AZ, Spring 2010
-- This code is covered by the ISC License:
--
-- Copyright (c) 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Lumen.Internal;
package Lumen.Window is
-- Handle for a Lumen window
subtype Handle is Internal.Window_Info;
-- Handle for an OpenGL rendering context
subtype Context_Handle is Internal.GLX_Context;
-- Null window; in X, this means the root window is the parent
No_Window : constant Handle := (Display => Internal.Null_Display_Pointer,
Window => 0,
Visual => null,
Width => 0,
Height => 0,
Context => Internal.Null_Context);
-- Means "no GL context"; for Create, means create a new one
No_Context : constant Context_Handle := Internal.Null_Context;
-- Types of events wanted, and a set listing them.
type Wanted_Event is (Want_Key_Press, Want_Key_Release, Want_Button_Press, Want_Button_Release,
Want_Window_Enter, Want_Window_Leave,
Want_Pointer_Move, Want_Pointer_Drag,
Want_Exposure, Want_Focus_Change);
type Wanted_Event_Set is array (Wanted_Event) of Boolean;
Want_No_Events : Wanted_Event_Set := (others => False);
Want_All_Events : Wanted_Event_Set := (others => True);
-- Rendering context's color depth
type Color_Depth is (Pseudo_Color, True_Color);
-- Local exceptions raised by these procedures
Connection_Failed : exception; -- can't connect to X server
Context_Failed : exception; -- can't create or attach OpenGL context
-- Create a native window, with defaults for configuration intended to
-- create a "usable" window. Details about the parameters are:
--
-- Parent: Handle of an existing window that will act as the new window's
-- parent, or No_Window, meaning an independent top-level window.
--
-- Width, Height: Window dimensions in pixels.
--
-- Events: Set of events this window wishes to receive.
--
-- Name: Name associated with new window, often displayed in the window's
-- title bar. If blank, the executable's filename is used.
--
-- Icon_Name: Name associated with the window's icon. If blank, the
-- executable's filename is used.
--
-- Class_Name, Instance_Name: Together these make up the window's "class".
-- If blank, the class name is set to the executable's filename with
-- initial capitalization; the instance name is set to the executable's
-- filename.
--
-- Context: An existing GL rendering context to be used in the new window,
-- or No_Context, meaning a new context is created for the window.
--
-- Depth: The color depth of the GL rendering context, either true-color or
-- indexed/pseudo-color.
--
-- Animated: Whether the GL rendering context will be double-buffered, thus
-- allowing smooth animation.
function Create (Parent : Handle := No_Window;
Width : Natural := 400;
Height : Natural := 400;
Events : Wanted_Event_Set := Want_No_Events;
Name : String := "";
Icon_Name : String := "";
Class_Name : String := "";
Instance_Name : String := "";
Context : Context_Handle := No_Context;
Depth : Color_Depth := True_Color;
Animated : Boolean := True)
return Handle;
-- Destroy a native window, including its current rendering context.
procedure Destroy (Win : in out Handle);
-- Set various textual names associated with a window. Null string means
-- leave the current value unchanged;
procedure Set_Names (Win : in Handle;
Name : in String := "";
Icon_Name : in String := "";
Class_Name : in String := "";
Instance_Name : in String := "");
-- Create an OpenGL rendering context; needed only when you want a second
-- or subsequent context for a window, since Create makes one to start
-- with
function Create_Context (Win : Handle) return Context_Handle;
-- Destroy a window's OpenGL rendering context; should be followed either
-- by a Make_Current or a Destroy_Window
procedure Destroy_Context (Win : in out Handle);
-- Make a rendering context the current one for a window
procedure Make_Current (Win : in out Handle;
Context : in Context_Handle);
-- Promotes the back buffer to front; only valid if the window is double
-- buffered, meaning Animated was true when the window was created. Useful
-- for smooth animation.
procedure Swap (Win : in Handle);
private
pragma Linker_Options ("-lX11");
pragma Linker_Options ("-lGL");
end Lumen.Window;
|
Add window width and height so we can recognize resizes
|
Add window width and height so we can recognize resizes
|
Ada
|
isc
|
darkestkhan/lumen2,darkestkhan/lumen
|
934e9be65a9f0d703cb55ef95d208832389786a1
|
src/natools-web-sites.adb
|
src/natools-web-sites.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. --
------------------------------------------------------------------------------
with Ada.Directories;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.Sites;
with Natools.Web.Pages;
package body Natools.Web.Sites is
procedure Add_Page
(Builder : in out Site_Builder;
File_Root : in S_Expressions.Atom;
Path_Root : in S_Expressions.Atom);
procedure Add_Page
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
File_Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Add_Page_Simple
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Common_Name : in S_Expressions.Atom);
procedure Get_Page
(Container : in Page_Maps.Updatable_Map;
Path : in S_Expressions.Atom;
Result : out Page_Maps.Cursor;
Extra_Path_First : out S_Expressions.Offset);
procedure Execute
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Set_If_Possible
(Reference : in out S_Expressions.Atom_Refs.Immutable_Reference;
Expression : in S_Expressions.Lockable.Descriptor'Class);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Get_Page
(Container : in Page_Maps.Updatable_Map;
Path : in S_Expressions.Atom;
Result : out Page_Maps.Cursor;
Extra_Path_First : out S_Expressions.Offset)
is
use type S_Expressions.Atom;
use type S_Expressions.Octet;
use type S_Expressions.Offset;
begin
Result := Container.Floor (Path);
if not Page_Maps.Has_Element (Result) then
Extra_Path_First := 0;
return;
end if;
declare
Found_Path : constant S_Expressions.Atom := Page_Maps.Key (Result);
begin
if Found_Path'Length > Path'Length
or else Path (Path'First .. Path'First + Found_Path'Length - 1)
/= Found_Path
then
Page_Maps.Clear (Result);
return;
end if;
Extra_Path_First := Path'First + Found_Path'Length;
end;
if Extra_Path_First in Path'Range
and then Path (Extra_Path_First) /= Character'Pos ('/')
then
Page_Maps.Clear (Result);
return;
end if;
end Get_Page;
procedure Set_If_Possible
(Reference : in out S_Expressions.Atom_Refs.Immutable_Reference;
Expression : in S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
begin
if Expression.Current_Event = S_Expressions.Events.Add_Atom then
Reference := S_Expressions.Atom_Ref_Constructors.Create
(Expression.Current_Atom);
end if;
end Set_If_Possible;
----------------------
-- Site Interpreter --
----------------------
procedure Add_Page
(Builder : in out Site_Builder;
File_Root : in S_Expressions.Atom;
Path_Root : in S_Expressions.Atom)
is
use type S_Expressions.Atom;
File : constant S_Expressions.Atom
:= Builder.File_Prefix.Query.Data.all
& File_Root
& Builder.File_Suffix.Query.Data.all;
Path : constant S_Expressions.Atom
:= Builder.Path_Prefix.Query.Data.all
& Path_Root
& Builder.Path_Suffix.Query.Data.all;
Page : constant Pages.Page_Ref := Pages.Create (File, Path);
begin
Builder.Pages.Insert (Path, Page);
end Add_Page;
procedure Add_Page
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
File_Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
begin
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Add_Page (Builder, File_Name, Arguments.Current_Atom);
end if;
end Add_Page;
procedure Add_Page_Simple
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Common_Name : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Add_Page (Builder, Common_Name, Common_Name);
end Add_Page_Simple;
procedure Add_Pages is new S_Expressions.Interpreter_Loop
(Site_Builder, Meaningless_Type, Add_Page, Add_Page_Simple);
procedure Execute
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.Sites;
use type S_Expressions.Events.Event;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Error =>
Log (Severities.Error, "Unknown site command """
& S_Expressions.To_String (Name) & '"');
when Commands.Set_Default_Template =>
Set_If_Possible (Builder.Default_Template, Arguments);
when Commands.Set_File_Prefix =>
Set_If_Possible (Builder.File_Prefix, Arguments);
when Commands.Set_File_Suffix =>
Set_If_Possible (Builder.File_Suffix, Arguments);
when Commands.Set_Path_Prefix =>
Set_If_Possible (Builder.Path_Prefix, Arguments);
when Commands.Set_Path_Suffix =>
Set_If_Possible (Builder.Path_Suffix, Arguments);
when Commands.Set_Static_Paths =>
Containers.Append_Atoms (Builder.Static, Arguments);
when Commands.Set_Template_File =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Arguments.Current_Atom));
begin
Containers.Set_Expressions (Builder.Templates, Reader);
end;
end if;
when Commands.Set_Templates =>
Containers.Set_Expressions (Builder.Templates, Arguments);
when Commands.Site_Map =>
Add_Pages (Arguments, Builder, Meaningless_Value);
end case;
end Execute;
procedure Interpreter is new S_Expressions.Interpreter_Loop
(Site_Builder, Meaningless_Type, Execute);
procedure Update
(Builder : in out Site_Builder;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Interpreter (Expression, Builder, Meaningless_Value);
end Update;
---------------------------
-- Site Public Interface --
---------------------------
function Create (File_Name : String) return Site is
Result : Site
:= (File_Name => S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.To_Atom (File_Name)),
others => <>);
begin
Reload (Result);
return Result;
end Create;
procedure Reload (Object : in out Site) is
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Object.File_Name.Query.Data.all));
Empty_Atom : constant S_Expressions.Atom_Refs.Immutable_Reference
:= S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.Null_Atom);
Builder : Site_Builder
:= (Default_Template
=> S_Expressions.Atom_Refs.Null_Immutable_Reference,
File_Prefix => Empty_Atom,
File_Suffix => Empty_Atom,
Path_Prefix => Empty_Atom,
Path_Suffix => Empty_Atom,
Pages | Static | Templates => <>);
begin
Update (Builder, Reader);
Object :=
(Default_Template => Builder.Default_Template,
File_Name => Object.File_Name,
Pages => Page_Maps.Create (Builder.Pages),
Static => Containers.Create (Builder.Static),
Templates => Builder.Templates);
if Object.Default_Template.Is_Empty then
Object.Default_Template := S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.To_Atom ("html"));
end if;
end Reload;
procedure Respond
(Object : aliased in out Site;
Exchange : in out Exchanges.Exchange)
is
use type S_Expressions.Octet;
use type S_Expressions.Offset;
procedure Call_Page
(Key : in S_Expressions.Atom;
Page_Object : in out Page'Class);
procedure Send_File_If_Exists (In_Directory : in S_Expressions.Atom);
Path : constant S_Expressions.Atom
:= S_Expressions.To_Atom (Exchanges.Path (Exchange));
procedure Call_Page
(Key : in S_Expressions.Atom;
Page_Object : in out Page'Class)
is
use type S_Expressions.Atom;
begin
pragma Assert (Key'Length <= Path'Length
and then Key = Path (Path'First .. Path'First + Key'Length - 1));
Respond (Page_Object, Exchange, Object,
Path (Path'First + Key'Length .. Path'Last));
end Call_Page;
procedure Send_File_If_Exists (In_Directory : in S_Expressions.Atom) is
use type S_Expressions.Atom;
Candidate_Name : constant S_Expressions.Atom := In_Directory & Path;
begin
if Ada.Directories.Exists
(S_Expressions.To_String (Candidate_Name))
then
Exchanges.Send_File (Exchange, Candidate_Name);
end if;
end Send_File_If_Exists;
Cursor : Page_Maps.Cursor;
Extra_Path_First : S_Expressions.Offset;
begin
if not Object.Static.Is_Empty then
for Path_Ref of Object.Static.Query.Data.all loop
Send_File_If_Exists (Path_Ref.Query.Data.all);
if Exchanges.Has_Response (Exchange) then
return;
end if;
end loop;
end if;
Get_Page (Object.Pages, Path, Cursor, Extra_Path_First);
if not Page_Maps.Has_Element (Cursor) then
return;
end if;
Response_Loop :
loop
Object.Pages.Update_Element (Cursor, Call_Page'Access);
exit Response_Loop when Exchanges.Has_Response (Exchange);
Find_Parent :
loop
Remove_Path_Component :
loop
Extra_Path_First := Extra_Path_First - 1;
exit Response_Loop
when Extra_Path_First not in Path'Range;
exit Remove_Path_Component
when Path (Extra_Path_First) = Character'Pos ('/');
end loop Remove_Path_Component;
Cursor := Object.Pages.Find
(Path (Path'First .. Extra_Path_First - 1));
exit Find_Parent when Page_Maps.Has_Element (Cursor);
end loop Find_Parent;
end loop Response_Loop;
end Respond;
-------------------------
-- Site Data Accessors --
-------------------------
procedure Get_Template
(Object : in Site;
Name : in S_Expressions.Atom;
Template : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Object.Templates.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Template := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Template;
function Default_Template (Object : Site) return S_Expressions.Atom is
begin
return Object.Default_Template.Query.Data.all;
end Default_Template;
end Natools.Web.Sites;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Directories;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.Sites;
with Natools.Web.Error_Pages;
with Natools.Web.Pages;
package body Natools.Web.Sites is
procedure Add_Page
(Builder : in out Site_Builder;
File_Root : in S_Expressions.Atom;
Path_Root : in S_Expressions.Atom);
procedure Add_Page
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
File_Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Add_Page_Simple
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Common_Name : in S_Expressions.Atom);
procedure Get_Page
(Container : in Page_Maps.Updatable_Map;
Path : in S_Expressions.Atom;
Result : out Page_Maps.Cursor;
Extra_Path_First : out S_Expressions.Offset);
procedure Execute
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Set_If_Possible
(Reference : in out S_Expressions.Atom_Refs.Immutable_Reference;
Expression : in S_Expressions.Lockable.Descriptor'Class);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Get_Page
(Container : in Page_Maps.Updatable_Map;
Path : in S_Expressions.Atom;
Result : out Page_Maps.Cursor;
Extra_Path_First : out S_Expressions.Offset)
is
use type S_Expressions.Atom;
use type S_Expressions.Octet;
use type S_Expressions.Offset;
begin
Result := Container.Floor (Path);
if not Page_Maps.Has_Element (Result) then
Extra_Path_First := 0;
return;
end if;
declare
Found_Path : constant S_Expressions.Atom := Page_Maps.Key (Result);
begin
if Found_Path'Length > Path'Length
or else Path (Path'First .. Path'First + Found_Path'Length - 1)
/= Found_Path
then
Page_Maps.Clear (Result);
return;
end if;
Extra_Path_First := Path'First + Found_Path'Length;
end;
if Extra_Path_First in Path'Range
and then Path (Extra_Path_First) /= Character'Pos ('/')
then
Page_Maps.Clear (Result);
return;
end if;
end Get_Page;
procedure Set_If_Possible
(Reference : in out S_Expressions.Atom_Refs.Immutable_Reference;
Expression : in S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
begin
if Expression.Current_Event = S_Expressions.Events.Add_Atom then
Reference := S_Expressions.Atom_Ref_Constructors.Create
(Expression.Current_Atom);
end if;
end Set_If_Possible;
----------------------
-- Site Interpreter --
----------------------
procedure Add_Page
(Builder : in out Site_Builder;
File_Root : in S_Expressions.Atom;
Path_Root : in S_Expressions.Atom)
is
use type S_Expressions.Atom;
File : constant S_Expressions.Atom
:= Builder.File_Prefix.Query.Data.all
& File_Root
& Builder.File_Suffix.Query.Data.all;
Path : constant S_Expressions.Atom
:= Builder.Path_Prefix.Query.Data.all
& Path_Root
& Builder.Path_Suffix.Query.Data.all;
Page : constant Pages.Page_Ref := Pages.Create (File, Path);
begin
Builder.Pages.Insert (Path, Page);
end Add_Page;
procedure Add_Page
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
File_Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
begin
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Add_Page (Builder, File_Name, Arguments.Current_Atom);
end if;
end Add_Page;
procedure Add_Page_Simple
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Common_Name : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Add_Page (Builder, Common_Name, Common_Name);
end Add_Page_Simple;
procedure Add_Pages is new S_Expressions.Interpreter_Loop
(Site_Builder, Meaningless_Type, Add_Page, Add_Page_Simple);
procedure Execute
(Builder : in out Site_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.Sites;
use type S_Expressions.Events.Event;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Error =>
Log (Severities.Error, "Unknown site command """
& S_Expressions.To_String (Name) & '"');
when Commands.Set_Default_Template =>
Set_If_Possible (Builder.Default_Template, Arguments);
when Commands.Set_File_Prefix =>
Set_If_Possible (Builder.File_Prefix, Arguments);
when Commands.Set_File_Suffix =>
Set_If_Possible (Builder.File_Suffix, Arguments);
when Commands.Set_Path_Prefix =>
Set_If_Possible (Builder.Path_Prefix, Arguments);
when Commands.Set_Path_Suffix =>
Set_If_Possible (Builder.Path_Suffix, Arguments);
when Commands.Set_Static_Paths =>
Containers.Append_Atoms (Builder.Static, Arguments);
when Commands.Set_Template_File =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Arguments.Current_Atom));
begin
Containers.Set_Expressions (Builder.Templates, Reader);
end;
end if;
when Commands.Set_Templates =>
Containers.Set_Expressions (Builder.Templates, Arguments);
when Commands.Site_Map =>
Add_Pages (Arguments, Builder, Meaningless_Value);
end case;
end Execute;
procedure Interpreter is new S_Expressions.Interpreter_Loop
(Site_Builder, Meaningless_Type, Execute);
procedure Update
(Builder : in out Site_Builder;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Interpreter (Expression, Builder, Meaningless_Value);
end Update;
---------------------------
-- Site Public Interface --
---------------------------
function Create (File_Name : String) return Site is
Result : Site
:= (File_Name => S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.To_Atom (File_Name)),
others => <>);
begin
Reload (Result);
return Result;
end Create;
procedure Reload (Object : in out Site) is
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Object.File_Name.Query.Data.all));
Empty_Atom : constant S_Expressions.Atom_Refs.Immutable_Reference
:= S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.Null_Atom);
Builder : Site_Builder
:= (Default_Template
=> S_Expressions.Atom_Refs.Null_Immutable_Reference,
File_Prefix => Empty_Atom,
File_Suffix => Empty_Atom,
Path_Prefix => Empty_Atom,
Path_Suffix => Empty_Atom,
Pages | Static | Templates => <>);
begin
Update (Builder, Reader);
Object :=
(Default_Template => Builder.Default_Template,
File_Name => Object.File_Name,
Pages => Page_Maps.Create (Builder.Pages),
Static => Containers.Create (Builder.Static),
Templates => Builder.Templates);
if Object.Default_Template.Is_Empty then
Object.Default_Template := S_Expressions.Atom_Ref_Constructors.Create
(S_Expressions.To_Atom ("html"));
end if;
end Reload;
procedure Respond
(Object : aliased in out Site;
Exchange : in out Exchanges.Exchange)
is
use type S_Expressions.Octet;
use type S_Expressions.Offset;
procedure Call_Page
(Key : in S_Expressions.Atom;
Page_Object : in out Page'Class);
procedure Send_File_If_Exists (In_Directory : in S_Expressions.Atom);
Path : constant S_Expressions.Atom
:= S_Expressions.To_Atom (Exchanges.Path (Exchange));
procedure Call_Page
(Key : in S_Expressions.Atom;
Page_Object : in out Page'Class)
is
use type S_Expressions.Atom;
begin
pragma Assert (Key'Length <= Path'Length
and then Key = Path (Path'First .. Path'First + Key'Length - 1));
Respond (Page_Object, Exchange, Object,
Path (Path'First + Key'Length .. Path'Last));
end Call_Page;
procedure Send_File_If_Exists (In_Directory : in S_Expressions.Atom) is
use type S_Expressions.Atom;
Candidate_Name : constant S_Expressions.Atom := In_Directory & Path;
begin
if Ada.Directories.Exists
(S_Expressions.To_String (Candidate_Name))
then
Exchanges.Send_File (Exchange, Candidate_Name);
end if;
end Send_File_If_Exists;
Cursor : Page_Maps.Cursor;
Extra_Path_First : S_Expressions.Offset;
begin
if not Object.Static.Is_Empty then
for Path_Ref of Object.Static.Query.Data.all loop
Send_File_If_Exists (Path_Ref.Query.Data.all);
if Exchanges.Has_Response (Exchange) then
return;
end if;
end loop;
end if;
Get_Page (Object.Pages, Path, Cursor, Extra_Path_First);
if not Page_Maps.Has_Element (Cursor) then
Error_Pages.Not_Found (Exchange, Object);
return;
end if;
Response_Loop :
loop
Object.Pages.Update_Element (Cursor, Call_Page'Access);
exit Response_Loop when Exchanges.Has_Response (Exchange);
Find_Parent :
loop
Remove_Path_Component :
loop
Extra_Path_First := Extra_Path_First - 1;
exit Response_Loop
when Extra_Path_First not in Path'Range;
exit Remove_Path_Component
when Path (Extra_Path_First) = Character'Pos ('/');
end loop Remove_Path_Component;
Cursor := Object.Pages.Find
(Path (Path'First .. Extra_Path_First - 1));
exit Find_Parent when Page_Maps.Has_Element (Cursor);
end loop Find_Parent;
end loop Response_Loop;
if not Exchanges.Has_Response (Exchange) then
Error_Pages.Not_Found (Exchange, Object);
end if;
end Respond;
-------------------------
-- Site Data Accessors --
-------------------------
procedure Get_Template
(Object : in Site;
Name : in S_Expressions.Atom;
Template : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Object.Templates.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Template := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Template;
function Default_Template (Object : Site) return S_Expressions.Atom is
begin
return Object.Default_Template.Query.Data.all;
end Default_Template;
end Natools.Web.Sites;
|
return 404 error when unable to find a responding page
|
sites: return 404 error when unable to find a responding page
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
7400e011fb2151e073423d0e6d5ef1093e8f41fe
|
samples/beans/users.adb
|
samples/beans/users.adb
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.Openid;
with Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.Openid;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.Openid;
with ASF.Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.Openid;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
Fix compilation after Ada Security integration
|
Fix compilation after Ada Security integration
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
7ffa3a7f0d099233267b4c47f62c2910e73bb1a5
|
src/util-locales.adb
|
src/util-locales.adb
|
-----------------------------------------------------------------------
-- Util.Locales -- Locale
-- Copyright (C) 2001, 2002, 2003, 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.Hash;
-- The <b>Locales</b> package defines the <b>Locale</b> type to represent
-- the language, country and variant.
--
-- The language is a valid <b>ISO language code</b>. This is a two-letter
-- lower case code defined by IS-639
-- See http://www.loc.gov/standards/iso639-2/englangn.html
--
-- The country is a valid <b>ISO country code</b>. These codes are
-- a two letter upper-case code defined by ISO-3166.
-- See http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
--
-- The variant part is a vendor or browser specific code.
--
-- The <b>Locales</b> package tries to follow the Java <b>Locale</b> class.
package body Util.Locales is
-- ------------------------------
-- Get the lowercase two-letter ISO-639 code.
-- ------------------------------
function Get_Language (Loc : in Locale) return String is
begin
if Loc = null then
return "";
else
return Loc (1 .. 2);
end if;
end Get_Language;
-- ------------------------------
-- Get the ISO 639-2 language code.
-- ------------------------------
function Get_ISO3_Language (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 3 then
return "";
end if;
if Loc'Length <= 6 then
return Loc (4 .. 6);
end if;
return Loc (7 .. 9);
end Get_ISO3_Language;
-- ------------------------------
-- Get the uppercase two-letter ISO-3166 code.
-- ------------------------------
function Get_Country (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then
return "";
else
return Loc (4 .. 5);
end if;
end Get_Country;
-- ------------------------------
-- Get the ISO-3166-2 country code.
-- ------------------------------
function Get_ISO3_Country (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 5 then
return "";
else
return Loc (10 .. Loc'Last);
end if;
end Get_ISO3_Country;
-- ------------------------------
-- Get the variant code
-- ------------------------------
function Get_Variant (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 13 then
return "";
else
return Loc (7 .. 8);
end if;
end Get_Variant;
-- ------------------------------
-- Get the locale for the given language code
-- ------------------------------
function Get_Locale (Language : in String) return Locale is
Length : constant Natural := Language'Length;
Lower : Natural := Locales'First;
Upper : Natural := Locales'Last;
Pos : Natural;
Result : Locale;
begin
while Lower <= Upper loop
Pos := (Lower + Upper) / 2;
Result := Locales (Pos);
if Result'Length < Length then
if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then
Lower := Pos + 1;
else
Upper := Pos - 1;
end if;
elsif Result'Length > Length and then Result (Length + 1) = '.'
and then Result (1 .. Length) = Language then
return Result;
elsif Result (1 .. Length) < Language then
Lower := Pos + 1;
else
Upper := Pos - 1;
end if;
end loop;
return NULL_LOCALE;
end Get_Locale;
-- ------------------------------
-- Get the locale for the given language and country code
-- ------------------------------
function Get_Locale (Language : in String;
Country : in String) return Locale is
begin
if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then
return NULL_LOCALE;
elsif Country'Length = 0 then
return Get_Locale (Language);
else
return Get_Locale (Language & "_" & Country);
end if;
end Get_Locale;
-- ------------------------------
-- Get the locale for the given language, country and variant code
-- ------------------------------
function Get_Locale (Language : in String;
Country : in String;
Variant : in String) return Locale is
begin
if Language'Length /= 2
or else (Country'Length /= 0 and Country'Length /= 2)
or else (Variant'Length /= 0 and Variant'Length /= 2) then
return NULL_LOCALE;
end if;
if Country'Length = 0 and Variant'Length = 0 then
return Get_Locale (Language);
elsif Variant'Length = 0 then
return Get_Locale (Language, Country);
else
return Get_Locale (Language & "_" & Country & "_" & Variant);
end if;
end Get_Locale;
-- ------------------------------
-- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>.
-- ------------------------------
function To_String (Loc : in Locale) return String is
begin
if Loc = null then
return "";
elsif Loc'Length > 3 and Loc (3) = '.' then
return Loc (1 .. 2);
elsif Loc'Length > 6 and Loc (6) = '.' then
return Loc (1 .. 5);
else
return Loc (1 .. 8);
end if;
end To_String;
-- ------------------------------
-- Compute the hash value of the locale.
-- ------------------------------
function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
return Ada.Strings.Hash (Loc.all);
end Hash;
end Util.Locales;
|
-----------------------------------------------------------------------
-- Util.Locales -- Locale
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Hash;
-- The <b>Locales</b> package defines the <b>Locale</b> type to represent
-- the language, country and variant.
--
-- The language is a valid <b>ISO language code</b>. This is a two-letter
-- lower case code defined by IS-639
-- See http://www.loc.gov/standards/iso639-2/englangn.html
--
-- The country is a valid <b>ISO country code</b>. These codes are
-- a two letter upper-case code defined by ISO-3166.
-- See http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
--
-- The variant part is a vendor or browser specific code.
--
-- The <b>Locales</b> package tries to follow the Java <b>Locale</b> class.
package body Util.Locales is
-- ------------------------------
-- Get the lowercase two-letter ISO-639 code.
-- ------------------------------
function Get_Language (Loc : in Locale) return String is
begin
if Loc = null then
return "";
else
return Loc (1 .. 2);
end if;
end Get_Language;
-- ------------------------------
-- Get the ISO 639-2 language code.
-- ------------------------------
function Get_ISO3_Language (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 3 then
return "";
end if;
if Loc'Length <= 6 then
return Loc (4 .. 6);
end if;
return Loc (7 .. 9);
end Get_ISO3_Language;
-- ------------------------------
-- Get the uppercase two-letter ISO-3166 code.
-- ------------------------------
function Get_Country (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then
return "";
else
return Loc (4 .. 5);
end if;
end Get_Country;
-- ------------------------------
-- Get the ISO-3166-2 country code.
-- ------------------------------
function Get_ISO3_Country (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 5 then
return "";
else
return Loc (10 .. Loc'Last);
end if;
end Get_ISO3_Country;
-- ------------------------------
-- Get the variant code
-- ------------------------------
function Get_Variant (Loc : in Locale) return String is
begin
if Loc = null or else Loc'Length <= 13 then
return "";
else
return Loc (7 .. 8);
end if;
end Get_Variant;
-- ------------------------------
-- Get the locale for the given language code
-- ------------------------------
function Get_Locale (Language : in String) return Locale is
Length : constant Natural := Language'Length;
Lower : Natural := Locales'First;
Upper : Natural := Locales'Last;
Pos : Natural;
Result : Locale;
begin
while Lower <= Upper loop
Pos := (Lower + Upper) / 2;
Result := Locales (Pos);
if Result'Length < Length then
if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then
Lower := Pos + 1;
else
Upper := Pos - 1;
end if;
elsif Result'Length > Length and then Result (Length + 1) = '.'
and then Result (1 .. Length) = Language
then
return Result;
elsif Result (1 .. Length) < Language then
Lower := Pos + 1;
else
Upper := Pos - 1;
end if;
end loop;
return NULL_LOCALE;
end Get_Locale;
-- ------------------------------
-- Get the locale for the given language and country code
-- ------------------------------
function Get_Locale (Language : in String;
Country : in String) return Locale is
begin
if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then
return NULL_LOCALE;
elsif Country'Length = 0 then
return Get_Locale (Language);
else
return Get_Locale (Language & "_" & Country);
end if;
end Get_Locale;
-- ------------------------------
-- Get the locale for the given language, country and variant code
-- ------------------------------
function Get_Locale (Language : in String;
Country : in String;
Variant : in String) return Locale is
begin
if Language'Length /= 2
or else (Country'Length /= 0 and Country'Length /= 2)
or else (Variant'Length /= 0 and Variant'Length /= 2)
then
return NULL_LOCALE;
end if;
if Country'Length = 0 and Variant'Length = 0 then
return Get_Locale (Language);
elsif Variant'Length = 0 then
return Get_Locale (Language, Country);
else
return Get_Locale (Language & "_" & Country & "_" & Variant);
end if;
end Get_Locale;
-- ------------------------------
-- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>.
-- ------------------------------
function To_String (Loc : in Locale) return String is
begin
if Loc = null then
return "";
elsif Loc'Length > 3 and Loc (3) = '.' then
return Loc (1 .. 2);
elsif Loc'Length > 6 and Loc (6) = '.' then
return Loc (1 .. 5);
else
return Loc (1 .. 8);
end if;
end To_String;
-- ------------------------------
-- Compute the hash value of the locale.
-- ------------------------------
function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
return Ada.Strings.Hash (Loc.all);
end Hash;
end Util.Locales;
|
Fix compilation style warning
|
Fix compilation style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
efcbf3fe26efb2f21b98e95cf4523f28d1581fd7
|
regtests/util-texts-builders_tests.adb
|
regtests/util-texts-builders_tests.adb
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Util.Test_Caller;
with Util.Texts.Builders;
with Util.Measures;
package body Util.Texts.Builders_Tests is
package String_Builder is new Util.Texts.Builders (Element_Type => Character,
Input => String,
Chunk_Size => 100);
package Caller is new Util.Test_Caller (Test, "Texts.Builders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length",
Test_Length'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append",
Test_Append'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear",
Test_Clear'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate",
Test_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail",
Test_Tail'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf",
Test_Perf'Access);
end Add_Tests;
-- ------------------------------
-- Test the length operation.
-- ------------------------------
procedure Test_Length (T : in out Test) is
B : String_Builder.Builder (10);
begin
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity");
end Test_Length;
-- ------------------------------
-- Test the append operation.
-- ------------------------------
procedure Test_Append (T : in out Test) is
S : constant String := "0123456789";
B : String_Builder.Builder (3);
begin
String_Builder.Append (B, "a string");
Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
-- Append new string and check content.
String_Builder.Append (B, " b string");
Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B),
"Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
for I in S'Range loop
String_Builder.Append (B, S (I));
end loop;
Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append");
end Test_Append;
-- ------------------------------
-- Test the clear operation.
-- ------------------------------
procedure Test_Clear (T : in out Test) is
B : String_Builder.Builder (7);
begin
for I in 1 .. 10 loop
String_Builder.Append (B, "a string");
end loop;
Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear");
Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear");
end Test_Clear;
-- ------------------------------
-- Test the tail operation.
-- ------------------------------
procedure Test_Tail (T : in out Test) is
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural);
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural) is
P : constant String := "0123456789";
B : String_Builder.Builder (Min);
begin
for I in 1 .. Max loop
String_Builder.Append (B, P (1 + (I mod 10)));
end loop;
declare
S : constant String := String_Builder.Tail (B, L);
S2 : constant String := String_Builder.To_Array (B);
begin
Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length");
if L >= Max then
Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result");
else
Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S,
"Invalid Tail result {"
& Positive'Image (Min) & ","
& Positive'Image (Max) & ","
& Positive'Image (L) & "]");
end if;
end;
end Check_Tail;
begin
for I in 1 .. 100 loop
for J in 1 .. 8 loop
for K in 1 .. I + 3 loop
Check_Tail (J, I, K);
end loop;
end loop;
end loop;
end Test_Tail;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
procedure Process (S : in String);
procedure Process2 (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
R2 : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
procedure Process2 (S : in String) is
begin
Ada.Strings.Unbounded.Append (R2, S);
end Process2;
procedure Get is new String_Builder.Inline_Iterate (Process2);
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
String_Builder.Iterate (B, Process'Access);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
Get (B);
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R2), "Invalid Inline_Iterate");
end Test_Iterate;
-- ------------------------------
-- Test the append and iterate performance.
-- ------------------------------
procedure Test_Perf (T : in out Test) is
Perf : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string-append.csv"));
Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time");
for Block_Size in 1 .. 300 loop
declare
B : String_Builder.Builder (10);
N : constant String := Natural'Image (Block_Size * 10) & ",";
begin
String_Builder.Set_Block_Size (B, Block_Size * 10);
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
end;
declare
S : Util.Measures.Stamp;
R : constant String := String_Builder.To_Array (B);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (R'Length > 0, "Invalid string length");
end;
declare
Count : Natural := 0;
procedure Process (Item : in String);
procedure Process (Item : in String) is
pragma Unreferenced (Item);
begin
Count := Count + 1;
end Process;
S : Util.Measures.Stamp;
begin
String_Builder.Iterate (B, Process'Access);
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (Count > 0, "The string builder was empty");
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
Ada.Text_IO.Close (Perf);
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string.csv"));
Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512),"
& "Append (1024),Unbounded,Iterate Time");
for I in 1 .. 4000 loop
declare
N : constant String := Natural'Image (I) & ",";
B : String_Builder.Builder (10);
B2 : String_Builder.Builder (10);
B3 : String_Builder.Builder (10);
U : Ada.Strings.Unbounded.Unbounded_String;
S : Util.Measures.Stamp;
begin
for J in 1 .. I loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B2, 512);
for J in 1 .. I loop
String_Builder.Append (B2, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B3, 1024);
for J in 1 .. I loop
String_Builder.Append (B3, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
for J in 1 .. I loop
Ada.Strings.Unbounded.Append (U, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
declare
R : constant String := String_Builder.To_Array (B);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
declare
R : constant String := Ada.Strings.Unbounded.To_String (U);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
end Test_Perf;
end Util.Texts.Builders_Tests;
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Util.Test_Caller;
with Util.Texts.Builders;
with Util.Measures;
package body Util.Texts.Builders_Tests is
package String_Builder is new Util.Texts.Builders (Element_Type => Character,
Input => String,
Chunk_Size => 100);
package Caller is new Util.Test_Caller (Test, "Texts.Builders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length",
Test_Length'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append",
Test_Append'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear",
Test_Clear'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate",
Test_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Iterate",
Test_Inline_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail",
Test_Tail'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf",
Test_Perf'Access);
end Add_Tests;
-- ------------------------------
-- Test the length operation.
-- ------------------------------
procedure Test_Length (T : in out Test) is
B : String_Builder.Builder (10);
begin
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity");
end Test_Length;
-- ------------------------------
-- Test the append operation.
-- ------------------------------
procedure Test_Append (T : in out Test) is
S : constant String := "0123456789";
B : String_Builder.Builder (3);
begin
String_Builder.Append (B, "a string");
Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
-- Append new string and check content.
String_Builder.Append (B, " b string");
Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B),
"Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
for I in S'Range loop
String_Builder.Append (B, S (I));
end loop;
Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append");
end Test_Append;
-- ------------------------------
-- Test the clear operation.
-- ------------------------------
procedure Test_Clear (T : in out Test) is
B : String_Builder.Builder (7);
begin
for I in 1 .. 10 loop
String_Builder.Append (B, "a string");
end loop;
Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear");
Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear");
end Test_Clear;
-- ------------------------------
-- Test the tail operation.
-- ------------------------------
procedure Test_Tail (T : in out Test) is
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural);
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural) is
P : constant String := "0123456789";
B : String_Builder.Builder (Min);
begin
for I in 1 .. Max loop
String_Builder.Append (B, P (1 + (I mod 10)));
end loop;
declare
S : constant String := String_Builder.Tail (B, L);
S2 : constant String := String_Builder.To_Array (B);
begin
Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length");
if L >= Max then
Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result");
else
Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S,
"Invalid Tail result {"
& Positive'Image (Min) & ","
& Positive'Image (Max) & ","
& Positive'Image (L) & "]");
end if;
end;
end Check_Tail;
begin
for I in 1 .. 100 loop
for J in 1 .. 8 loop
for K in 1 .. I + 3 loop
Check_Tail (J, I, K);
end loop;
end loop;
end loop;
end Test_Tail;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
String_Builder.Iterate (B, Process'Access);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Iterate;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Inline_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
procedure Get is new String_Builder.Inline_Iterate (Process);
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
Get (B);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Inline_Iterate;
-- ------------------------------
-- Test the append and iterate performance.
-- ------------------------------
procedure Test_Perf (T : in out Test) is
Perf : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string-append.csv"));
Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time");
for Block_Size in 1 .. 300 loop
declare
B : String_Builder.Builder (10);
N : constant String := Natural'Image (Block_Size * 10) & ",";
begin
String_Builder.Set_Block_Size (B, Block_Size * 10);
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
end;
declare
S : Util.Measures.Stamp;
R : constant String := String_Builder.To_Array (B);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (R'Length > 0, "Invalid string length");
end;
declare
Count : Natural := 0;
procedure Process (Item : in String);
procedure Process (Item : in String) is
pragma Unreferenced (Item);
begin
Count := Count + 1;
end Process;
S : Util.Measures.Stamp;
begin
String_Builder.Iterate (B, Process'Access);
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (Count > 0, "The string builder was empty");
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
Ada.Text_IO.Close (Perf);
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string.csv"));
Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512),"
& "Append (1024),Unbounded,Iterate Time");
for I in 1 .. 4000 loop
declare
N : constant String := Natural'Image (I) & ",";
B : String_Builder.Builder (10);
B2 : String_Builder.Builder (10);
B3 : String_Builder.Builder (10);
U : Ada.Strings.Unbounded.Unbounded_String;
S : Util.Measures.Stamp;
begin
for J in 1 .. I loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B2, 512);
for J in 1 .. I loop
String_Builder.Append (B2, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B3, 1024);
for J in 1 .. I loop
String_Builder.Append (B3, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
for J in 1 .. I loop
Ada.Strings.Unbounded.Append (U, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
declare
R : constant String := String_Builder.To_Array (B);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
declare
R : constant String := Ada.Strings.Unbounded.To_String (U);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
end Test_Perf;
end Util.Texts.Builders_Tests;
|
Add new test and register it for execution
|
Add new test and register it for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ee8872e238221840b599b10cd81376e46720ea65
|
src/security-controllers.ads
|
src/security-controllers.ads
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
-- <ul>
-- <li>Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- <li>Write a function to allocate instances of the given <b>Controller</b> type
-- <li>Register the function under a unique name by using <b>Register_Controller</b>
-- </ul>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared accross possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
-- <ul>
-- <li>Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- <li>Write a function to allocate instances of the given <b>Controller</b> type
-- <li>Register the function under a unique name by using <b>Register_Controller</b>
-- </ul>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared across possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
Fix typo in comment
|
Fix typo in comment
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
c9cb69bac98c063c0161b36a79c9ddc1029170fb
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
-- type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
private
use Util.Strings;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
end Security.Permissions;
|
Remove the operation and types which are now in Security.Policy
|
Remove the operation and types which are now in Security.Policy
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f495ee6609d058f413756a123ee2aac2509b722d
|
src/wiki-streams-html.ads
|
src/wiki-streams-html.ads
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- 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.Strings;
-- === HTML Output Stream ===
-- 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.Html is
type Html_Output_Stream is limited interface and Output_Stream;
type Html_Output_Stream_Access is access all Html_Output_Stream'Class;
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Wide_Element (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Writer : in out Html_Output_Stream'Class;
Name : in String;
Content : in String);
end Wiki.Streams.Html;
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- 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.Strings;
-- === HTML Output Stream ===
-- 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.Html is
type Html_Output_Stream is limited interface and Output_Stream;
type Html_Output_Stream_Access is access all Html_Output_Stream'Class;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Writer : in out Html_Output_Stream'Class;
Name : in String;
Content : in String);
end Wiki.Streams.Html;
|
Remove the Write_Wide_Element operation (not used)
|
Remove the Write_Wide_Element operation (not used)
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
fb0a7cd91109e9a8cd861e50960b0c13a4862df8
|
src/util-events-channels.ads
|
src/util-events-channels.ads
|
-----------------------------------------------------------------------
-- events-channel -- Event Channels
-- Copyright (C) 2001, 2002, 2003, 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.Strings.Unbounded;
with Ada.Containers.Doubly_Linked_Lists;
-- The <b>Util.Events.Channels</b> package implements a publish/subscribe event
-- channel. It is inspired from Event pattern and CosEvent service.
package Util.Events.Channels is
type Subscriber is limited interface;
type Subscriber_Access is access all Subscriber'Class;
procedure Receive_Event (Sub : in out Subscriber;
Item : in Event'Class) is abstract;
----------------------
-- Event Channel
----------------------
-- Channel on which events are pushed.
type Channel is tagged limited private;
type Channel_Access is access all Channel'Class;
-- Get the name of this event channel.
function Get_Name (C : Channel) return String;
-- Post an event (may be asynchronous)
procedure Post (To : in out Channel;
Item : in Event'Class);
-- Subscribe to events sent on the event channel.
procedure Subscribe (To : in out Channel;
Client : in Subscriber_Access);
-- Unsubscribe to events sent on the event channel.
procedure Unsubscribe (To : in out Channel;
Client : in Subscriber_Access);
type Channel_Creator is access
function (Name : String) return Channel_Access;
-- Create an event channel with the given name. The type of channel
-- is controlled by <b>Kind</b>.
function Create (Name : String;
Kind : String) return Channel_Access;
-- Create an event channel that post the event immediately.
-- This is similar to calling <b>Create</b> with <b>"direct"</b> as kind.
function Create_Direct_Channel (Name : String) return Channel_Access;
private
package Containers is new Ada.Containers.Doubly_Linked_Lists
(Element_Type => Subscriber_Access);
subtype List is Containers.List;
type Channel is tagged limited record
Name : Ada.Strings.Unbounded.Unbounded_String;
Clients : List;
end record;
end Util.Events.Channels;
|
-----------------------------------------------------------------------
-- util-events-channel -- Event Channels
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Doubly_Linked_Lists;
-- The <b>Util.Events.Channels</b> package implements a publish/subscribe event
-- channel. It is inspired from Event pattern and CosEvent service.
package Util.Events.Channels is
type Subscriber is limited interface;
type Subscriber_Access is access all Subscriber'Class;
procedure Receive_Event (Sub : in out Subscriber;
Item : in Event'Class) is abstract;
----------------------
-- Event Channel
----------------------
-- Channel on which events are pushed.
type Channel is tagged limited private;
type Channel_Access is access all Channel'Class;
-- Get the name of this event channel.
function Get_Name (C : Channel) return String;
-- Post an event (may be asynchronous)
procedure Post (To : in out Channel;
Item : in Event'Class);
-- Subscribe to events sent on the event channel.
procedure Subscribe (To : in out Channel;
Client : in Subscriber_Access);
-- Unsubscribe to events sent on the event channel.
procedure Unsubscribe (To : in out Channel;
Client : in Subscriber_Access);
type Channel_Creator is access
function (Name : String) return Channel_Access;
-- Create an event channel with the given name. The type of channel
-- is controlled by <b>Kind</b>.
function Create (Name : String;
Kind : String) return Channel_Access;
-- Create an event channel that post the event immediately.
-- This is similar to calling <b>Create</b> with <b>"direct"</b> as kind.
function Create_Direct_Channel (Name : String) return Channel_Access;
private
package Containers is new Ada.Containers.Doubly_Linked_Lists
(Element_Type => Subscriber_Access);
subtype List is Containers.List;
type Channel is tagged limited record
Name : Ada.Strings.Unbounded.Unbounded_String;
Clients : List;
end record;
end Util.Events.Channels;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
53e8fc62e05a02a69f4488c6c02e4cc53157513f
|
samples/demo_server.adb
|
samples/demo_server.adb
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Upload_Servlet;
with Countries;
with Volume;
with Messages;
with Facebook;
-- with Images;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Upload : aliased Upload_Servlet.Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Mapping (Name => "upload", Pattern => "upload.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Upload_Servlet;
with Countries;
with Volume;
with Messages;
with Facebook;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Upload : aliased Upload_Servlet.Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Mapping (Name => "upload", Pattern => "upload.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
8d6e081fefa862807b887b89daf7ec01ab4dd2fb
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the <w:like> component in the factory
|
Add the <w:like> component in the factory
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
db4ef3d8c87aed8edd1faf916d0ede46cd2ddcf7
|
src/gen-generator.ads
|
src/gen-generator.ads
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- 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 Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- 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 Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
Add an optional third string parameter to the Info procedure
|
Add an optional third string parameter to the Info procedure
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
1c46a94ccad9194d15356a007d98e5f89e5989a6
|
src/sys/streams/util-streams-pipes.ads
|
src/sys/streams/util-streams-pipes.ads
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
Fix the stream documentation
|
Fix the stream documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
61716426ee354e9df3cb5455ccc0a160a8c4b8f9
|
tests/natools-smaz-tests.adb
|
tests/natools-smaz-tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
Buffer : Ada.Streams.Stream_Element_Array
(1 .. Compressed_Upper_Bound (Dict, Decompressed) + 10);
Last : Ada.Streams.Stream_Element_Offset;
Done : Boolean := False;
begin
begin
Compress (Dict, Decompressed, Buffer, Last);
Done := True;
exception
when Error : others =>
Test.Info ("During compression of """ & Decompressed & '"');
Test.Report_Exception (Error, NT.Fail);
end;
if Done and then Buffer (1 .. Last) /= Compressed then
Test.Fail ("Compression of """ & Decompressed & """ failed");
Test.Info ("Found: " & Image (Buffer (1 .. Last)));
Test.Info ("Expected:" & Image (Compressed));
end if;
declare
Buffer_2 : String
(1 .. Decompressed_Length (Dict, Buffer (1 .. Last)));
Last_2 : Natural;
Done : Boolean := False;
begin
begin
Decompress (Dict, Buffer (1 .. Last), Buffer_2, Last_2);
Done := True;
exception
when Error : others =>
Test.Info ("During compression of """ & Decompressed & '"');
Test.Report_Exception (Error, NT.Fail);
end;
if Done and then Buffer_2 (1 .. Last_2) /= Decompressed then
Test.Fail ("Roundtrip for """ & Decompressed & """ failed");
Test.Info ("Found """ & Buffer_2 (1 .. Last_2) & '"');
end if;
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 1, 48, 48, 24, 204, 254, 69, 250, 4, 45,
60, 22, 255, 2, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 1, 49, 48, 0, 255, 1, 50, 48, 0, 255, 1, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 1, 48, 48, 24, 204, 254, 69, 250, 4, 45,
60, 22, 255, 2, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 1, 49, 48, 0, 255, 1, 50, 48, 0, 255, 1, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
rewrite Roundtrip_Test to make both roundtrip directions
|
smaz-tests: rewrite Roundtrip_Test to make both roundtrip directions
|
Ada
|
isc
|
faelys/natools
|
bdbd90dbb81c79dccea2ecf902d592b7a5dcba16
|
src/sys/streams/util-streams-texts.adb
|
src/sys/streams/util-streams-texts.adb
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2016, 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.IO_Exceptions;
package body Util.Streams.Texts is
use Ada.Streams;
procedure Initialize (Stream : in out Print_Stream;
To : access Output_Stream'Class) is
begin
Stream.Initialize (Output => To, Size => 4096);
end Initialize;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write_Wide (C);
end loop;
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character) is
begin
Stream.Write (Item);
end Write_Char;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character) is
begin
Stream.Write_Wide (Item);
end Write_Char;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : access Input_Stream'Class) is
begin
Stream.Initialize (Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Texts is
use Ada.Streams;
procedure Initialize (Stream : in out Print_Stream;
To : access Output_Stream'Class) is
begin
Stream.Initialize (Output => To, Size => 4096);
end Initialize;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write_Wide (C);
end loop;
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item >= 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item >= 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character) is
begin
Stream.Write (Item);
end Write_Char;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character) is
begin
Stream.Write_Wide (Item);
end Write_Char;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : access Input_Stream'Class) is
begin
Stream.Initialize (Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
Fix Write (Integer) to avoid spurious Ada space when writing a '0'
|
Fix Write (Integer) to avoid spurious Ada space when writing a '0'
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2ed6d0253bd53fcf6d61f8c195683d04a3eba4e8
|
awa/plugins/awa-storages/src/awa-storages.ads
|
awa/plugins/awa-storages/src/awa-storages.ads
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- 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.Strings.Unbounded;
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A data in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
-- To save a file in the store, we can use the `Save` operation of the storage service.
-- It will read the file and put in in the corresponding persistent store (the database
-- in this example).
--
-- Service.Save (Into => Data, Path => Path_To_The_File,
-- Storage => AWA.Storages.Models.DATABASE);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Getting the data ==
-- Several operations are defined to retrieve the data. Each of them has been designed
-- to optimize the retrieval and
--
-- * The data can be retrieved in a local file.
-- This mode is useful if an external program must be launched and be able to read
-- the file. If the storage mode of the data is `FILE`, the path of the file on
-- the storage file system is used. For other storage modes, the file is saved
-- in a temporary file. In that case the `Store_Local` database table is used
-- to track such locally saved data.
--
-- * The data can be returned as a stream.
-- When the application has to read the data, opening a read stream connection is
-- the most efficient mechanism.
--
-- === Local file ===
-- To access the data by using a local file, we must define a local storage reference:
--
-- Data : AWA.Storages.Models.Store_Local_Ref;
--
-- and use the `Load` operation with the storage identifier. When loading locally we
-- also indicate whether the file will be read or written. A file that is in `READ` mode
-- can be shared by several tasks or processes. A file that is in `WRITE` mode will have
-- a specific copy for the caller. An optional expiration parameter indicate when the
-- local file representation can expire.
--
-- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY);
--
-- Once the load operation succeeded, the data is stored on the file system and
-- the local path is obtained by using the `Get_Path` operation:
--
-- Path : constant String := Data.Get_Path;
--
-- @include awa-storages-modules.ads
-- @include awa-storages-services.ads
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [images/awa_storage_model.png]
--
-- @include storage-list.xml
-- @include folder-queries.xml
-- @include storage-queries.xml
--
package AWA.Storages is
type Storage_File is limited private;
-- Get the path to get access to the file.
function Get_Path (File : in Storage_File) return String;
private
type Storage_File is limited record
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Storages;
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A data in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
-- To save a file in the store, we can use the `Save` operation of the storage service.
-- It will read the file and put in in the corresponding persistent store (the database
-- in this example).
--
-- Service.Save (Into => Data, Path => Path_To_The_File,
-- Storage => AWA.Storages.Models.DATABASE);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Getting the data ==
-- Several operations are defined to retrieve the data. Each of them has been designed
-- to optimize the retrieval and
--
-- * The data can be retrieved in a local file.
-- This mode is useful if an external program must be launched and be able to read
-- the file. If the storage mode of the data is `FILE`, the path of the file on
-- the storage file system is used. For other storage modes, the file is saved
-- in a temporary file. In that case the `Store_Local` database table is used
-- to track such locally saved data.
--
-- * The data can be returned as a stream.
-- When the application has to read the data, opening a read stream connection is
-- the most efficient mechanism.
--
-- === Local file ===
-- To access the data by using a local file, we must define a local storage reference:
--
-- Data : AWA.Storages.Models.Store_Local_Ref;
--
-- and use the `Load` operation with the storage identifier. When loading locally we
-- also indicate whether the file will be read or written. A file that is in `READ` mode
-- can be shared by several tasks or processes. A file that is in `WRITE` mode will have
-- a specific copy for the caller. An optional expiration parameter indicate when the
-- local file representation can expire.
--
-- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY);
--
-- Once the load operation succeeded, the data is stored on the file system and
-- the local path is obtained by using the `Get_Path` operation:
--
-- Path : constant String := Data.Get_Path;
--
-- @include awa-storages-modules.ads
-- @include awa-storages-services.ads
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [images/awa_storage_model.png]
--
-- @include storage-list.xml
-- @include folder-queries.xml
-- @include storage-queries.xml
--
package AWA.Storages is
type Storage_File is limited private;
-- Get the path to get access to the file.
function Get_Path (File : in Storage_File) return String;
type Temporary_File is limited private;
-- Get the path to get access to the file.
function Get_Path (File : in Temporary_File) return String;
private
type Storage_File is limited record
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Temporary_File is limited new Ada.Finalization.Limited_Controlled with record
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Finalize (File : in out Temporary_File);
end AWA.Storages;
|
Define Temporary_File type for a temporary file to be deleted when the object is destroyed
|
Define Temporary_File type for a temporary file to be deleted when the object is destroyed
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
81c2263e552e840451bcfc9a67659749fb1bbe3f
|
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 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 AWA.Applications.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;
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;
|
Update Configure to allow configuration of ASF application
|
Update Configure to allow configuration of ASF application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0431d91f082de3addc89d9956b5b913127152f67
|
regtests/dlls/util-systems-dlls-tests.adb
|
regtests/dlls/util-systems-dlls-tests.adb
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013, 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.Test_Caller;
with Util.Systems.Os;
package body Util.Systems.DLLs.Tests is
use Util.Tests;
use type System.Address;
function Get_Test_Symbol return String;
package Caller is new Util.Test_Caller (Test, "Systems.Dlls");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load",
Test_Load'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol",
Test_Get_Symbol'Access);
end Add_Tests;
function Get_Test_Symbol return String is
begin
pragma Warnings (Off);
if Util.Systems.Os.Directory_Separator = '/' then
return "EVP_sha1";
else
return "compress";
end if;
pragma Warnings (On);
end Get_Test_Symbol;
procedure Load_Library (T : in out Test;
Lib : out Handle) is
Lib1 : Handle;
Lib2 : Handle;
Lib3 : Handle;
begin
begin
Lib1 := Util.Systems.DLLs.Load ("libcrypto.so");
T.Assert (Lib1 /= Null_Handle, "Load operation returned null");
Lib := Lib1;
exception
when Load_Error =>
Lib1 := Null_Handle;
end;
begin
Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib2;
exception
when Load_Error =>
Lib2 := Null_Handle;
end;
begin
Lib3 := Util.Systems.DLLs.Load ("zlib1.dll");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib3;
exception
when Load_Error =>
Lib3 := Null_Handle;
end;
T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 = Null_Handle,
"At least on Load operation should have failedreturned null");
end Load_Library;
-- ------------------------------
-- Test the loading a shared library.
-- ------------------------------
procedure Test_Load (T : in out Test) is
Lib : Handle;
begin
Load_Library (T, Lib);
begin
Lib := Util.Systems.DLLs.Load ("some-invalid-library");
T.Fail ("Load must raise an exception");
exception
when Load_Error =>
null;
end;
end Test_Load;
-- ------------------------------
-- Test getting a shared library symbol.
-- ------------------------------
procedure Test_Get_Symbol (T : in out Test) is
Lib : Handle;
Sym : System.Address := System.Null_Address;
begin
Load_Library (T, Lib);
T.Assert (Lib /= Null_Handle, "Load operation returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
-- We must have found one of the two symbols
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol");
T.Fail ("The Get_Symbol operation must raise an exception");
exception
when Not_Found =>
null;
end;
end Test_Get_Symbol;
end Util.Systems.DLLs.Tests;
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013, 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.Test_Caller;
package body Util.Systems.DLLs.Tests is
use Util.Tests;
use type System.Address;
package Caller is new Util.Test_Caller (Test, "Systems.Dlls");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load",
Test_Load'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol",
Test_Get_Symbol'Access);
end Add_Tests;
procedure Load_Library (T : in out Test;
Lib : out Handle) is
Lib1 : Handle;
Lib2 : Handle;
Lib3 : Handle;
begin
begin
Lib1 := Util.Systems.DLLs.Load ("libcrypto.so");
T.Assert (Lib1 /= Null_Handle, "Load operation returned null");
Lib := Lib1;
exception
when Load_Error =>
Lib1 := Null_Handle;
end;
begin
Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib2;
exception
when Load_Error =>
Lib2 := Null_Handle;
end;
begin
Lib3 := Util.Systems.DLLs.Load ("zlib1.dll");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib3;
exception
when Load_Error =>
Lib3 := Null_Handle;
end;
T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 = Null_Handle,
"At least on Load operation should have failedreturned null");
end Load_Library;
-- ------------------------------
-- Test the loading a shared library.
-- ------------------------------
procedure Test_Load (T : in out Test) is
Lib : Handle;
begin
Load_Library (T, Lib);
begin
Lib := Util.Systems.DLLs.Load ("some-invalid-library");
T.Fail ("Load must raise an exception");
exception
when Load_Error =>
null;
end;
end Test_Load;
-- ------------------------------
-- Test getting a shared library symbol.
-- ------------------------------
procedure Test_Get_Symbol (T : in out Test) is
Lib : Handle;
Sym : System.Address := System.Null_Address;
begin
Load_Library (T, Lib);
T.Assert (Lib /= Null_Handle, "Load operation returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
-- We must have found one of the two symbols
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol");
T.Fail ("The Get_Symbol operation must raise an exception");
exception
when Not_Found =>
null;
end;
end Test_Get_Symbol;
end Util.Systems.DLLs.Tests;
|
Fix compilation warning and remove Get_Test_Symbol
|
Fix compilation warning and remove Get_Test_Symbol
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
97e6cfe2fe65873a31b6f22dd9090ba20039ec51
|
src/sys/os-windows/util-streams-raw.ads
|
src/sys/os-windows/util-streams-raw.ads
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Windows based systems
-- Copyright (C) 2011, 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.Finalization;
with Util.Systems.Os;
-- The <b>Util.Streams.Raw</b> package provides a stream directly on top of
-- file system operations <b>ReadFile</b> and <b>WriteFile</b>.
package Util.Streams.Raw is
subtype File_Type is Util.Systems.Os.File_Type;
-- -----------------------
-- File stream
-- -----------------------
-- The <b>Raw_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream
and Input_Stream with private;
type Raw_Stream_Access is access all Raw_Stream'Class;
-- Initialize the raw stream to read and write on the given file descriptor.
procedure Initialize (Stream : in out Raw_Stream;
File : in File_Type);
-- Get the file descriptor associated with the stream.
function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type;
-- Set the file descriptor to be used by the stream.
procedure Set_File (Stream : in out Raw_Stream;
File : in Util.Systems.Os.File_Type);
-- Close the stream.
overriding
procedure Close (Stream : in out Raw_Stream);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Raw_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Raw_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Raw_Stream);
type Raw_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : File_Type := Util.Systems.Os.NO_FILE;
end record;
end Util.Streams.Raw;
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Windows based systems
-- Copyright (C) 2011, 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.Finalization;
with Util.Systems.Os;
-- The <b>Util.Streams.Raw</b> package provides a stream directly on top of
-- file system operations <b>ReadFile</b> and <b>WriteFile</b>.
package Util.Streams.Raw is
subtype File_Type is Util.Systems.Os.File_Type;
-- -----------------------
-- File stream
-- -----------------------
-- The <b>Raw_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream
and Input_Stream with private;
type Raw_Stream_Access is access all Raw_Stream'Class;
-- Initialize the raw stream to read and write on the given file descriptor.
procedure Initialize (Stream : in out Raw_Stream;
File : in File_Type);
-- Get the file descriptor associated with the stream.
function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type;
-- Set the file descriptor to be used by the stream.
procedure Set_File (Stream : in out Raw_Stream;
File : in Util.Systems.Os.File_Type);
-- Close the stream.
overriding
procedure Close (Stream : in out Raw_Stream);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Raw_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Raw_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Reposition the read/write file offset.
procedure Seek (Stream : in out Raw_Stream;
Pos : in Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode);
private
use Ada.Streams;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Raw_Stream);
type Raw_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : File_Type := Util.Systems.Os.NO_FILE;
end record;
end Util.Streams.Raw;
|
Declare the Seek procedure
|
Declare the Seek procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8c9633e3a6082f5c87d716c353df409aba9f34da
|
src/gen-artifacts-distribs-copies.ads
|
src/gen-artifacts-distribs-copies.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-copies -- Copy based distribution artifact
-- 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.
-----------------------------------------------------------------------
-- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules
-- to copy a file or a directory to the distribution area.
private package Gen.Artifacts.Distribs.Copies is
-- Create a distribution rule to copy a set of files or directories.
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Copy_Rule is new Distrib_Rule with private;
type Copy_Rule_Access is access all Copy_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
overriding
function Get_Install_Name (Rule : in Copy_Rule) return String;
overriding
procedure Install (Rule : in Copy_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class);
private
type Copy_Rule is new Distrib_Rule with null record;
end Gen.Artifacts.Distribs.Copies;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-copies -- Copy based distribution artifact
-- 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.
-----------------------------------------------------------------------
-- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules
-- to copy a file or a directory to the distribution area.
private package Gen.Artifacts.Distribs.Copies is
-- Create a distribution rule to copy a set of files or directories.
function Create_Rule (Node : in DOM.Core.Node;
Copy_First_File : in Boolean) return Distrib_Rule_Access;
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Copy_Rule is new Distrib_Rule with private;
type Copy_Rule_Access is access all Copy_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
overriding
function Get_Install_Name (Rule : in Copy_Rule) return String;
overriding
procedure Install (Rule : in Copy_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class);
private
type Copy_Rule is new Distrib_Rule with record
-- When True and there are several source files, use the first file.
-- Otherwise, use the last file.
Copy_First_File : Boolean := False;
end record;
end Gen.Artifacts.Distribs.Copies;
|
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
|
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
03c3a75ee5eba1519591a0d8b1d38e6fc82f5dd0
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
protected body Memory_Allocator is
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Old_Slot : Allocation;
Pos : Allocation_Cursor;
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
begin
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
begin
if Old_Addr /= 0 then
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out Size_Info_Map) is
Iter : Allocation_Cursor := Used_Slots.First;
procedure Update_Count (Size : in MAT.Types.Target_Size;
Info : in out Size_Info_Type) is
begin
Info.Count := Info.Count + 1;
end Update_Count;
procedure Collect (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Pos : Size_Info_Cursor := Sizes.Find (Slot.Size);
begin
if Size_Info_Maps.Has_Element (Pos) then
Sizes.Update_Element (Pos, Update_Count'Access);
else
declare
Info : Size_Info_Type;
begin
Info.Count := 1;
Sizes.Insert (Slot.Size, Info);
end;
end if;
end Collect;
begin
while Allocation_Maps.Has_Element (Iter) loop
Allocation_Maps.Query_Element (Iter, Collect'Access);
Allocation_Maps.Next (Iter);
end loop;
end Size_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
protected body Memory_Allocator is
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Old_Slot : Allocation;
Pos : Allocation_Cursor;
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
begin
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
begin
if Old_Addr /= 0 then
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Use the Size_Information implemented in MAT.Memory.Tools
|
Use the Size_Information implemented in MAT.Memory.Tools
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
58404aeca80979cc1d5e6120cfd725d9f5b6f9ad
|
awa/plugins/awa-setup/src/awa-setup-applications.adb
|
awa/plugins/awa-setup/src/awa-setup-applications.adb
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings;
with ASF.Events.Faces.Actions;
with ASF.Applications.Main.Configs;
with AWA.Applications;
package body AWA.Setup.Applications is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications");
package Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Save,
Name => "save");
package Finish_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Finish,
Name => "finish");
package Configure_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Configure_Database,
Name => "configure_database");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Save_Binding.Proxy'Access,
Finish_Binding.Proxy'Access,
Configure_Binding.Proxy'Access);
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "database_name" then
return Util.Beans.Objects.To_Object (From.Database.Get_Database);
elsif Name = "database_server" then
return Util.Beans.Objects.To_Object (From.Database.Get_Server);
elsif Name = "database_port" then
return Util.Beans.Objects.To_Object (From.Database.Get_Port);
elsif Name = "database_user" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user"));
elsif Name = "database_password" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password"));
end if;
if From.Changed.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name)));
end if;
declare
Param : constant String := From.Config.Get (Name);
begin
return Util.Beans.Objects.To_Object (Param);
end;
exception
when others =>
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "database_name" then
From.Database.Set_Database (Util.Beans.Objects.To_String (Value));
elsif Name = "database_server" then
From.Database.Set_Server (Util.Beans.Objects.To_String (Value));
elsif Name = "database_port" then
From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value));
elsif Name = "database_user" then
From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value));
elsif Name = "database_password" then
From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value));
else
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Configure database");
end Configure_Database;
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Path : constant String := Ada.Strings.Unbounded.To_String (From.Path);
New_File : constant String := Path & ".tmp";
Output : Ada.Text_IO.File_Type;
procedure Read_Property (Line : in String) is
Pos : constant Natural := Util.Strings.Index (Line, '=');
begin
if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then
Ada.Text_IO.Put_Line (Line);
return;
end if;
Ada.Text_IO.Put (Line (Line'First .. Pos));
Ada.Text_IO.Put_Line (From.Changed.Get (Line (Line'First .. Pos - 1)));
end Read_Property;
begin
Log.Info ("Saving configuration file {0}", Path);
Ada.Text_IO.Create (File => Output, Name => Path);
Util.Files.Read_File (Path, Read_Property'Access);
Ada.Text_IO.Close (Output);
end Save;
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Finish configuration");
From.Done := True;
end Finish;
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access is
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class) is
begin
Log.Info ("Entering configuration for {0}", Config);
App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config);
begin
App.Config.Load_Properties (Config);
Util.Log.Loggers.Initialize (Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file: {0}", Config);
end;
App.Initialize (App.Config, App.Factory);
App.Set_Global ("contextPath", App.Config.Get ("contextPath"));
App.Set_Global ("setup",
Util.Beans.Objects.To_Object (App'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Add_Servlet (Name => "faces",
Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files",
Server => App.Files'Unchecked_Access);
App.Add_Mapping (Pattern => "*.html",
Name => "faces");
App.Add_Mapping (Pattern => "*.css",
Name => "files");
App.Add_Mapping (Pattern => "*.js",
Name => "files");
declare
Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P);
Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths);
begin
ASF.Applications.Main.Configs.Read_Configuration (App, Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Setup configuration file '{0}' does not exist", Path);
end;
App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db"));
Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access);
Server.Start;
while not App.Done loop
delay 5.0;
end loop;
end Setup;
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings;
with ASF.Events.Faces.Actions;
with ASF.Applications.Main.Configs;
with AWA.Applications;
package body AWA.Setup.Applications is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications");
package Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Save,
Name => "save");
package Finish_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Finish,
Name => "finish");
package Configure_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Configure_Database,
Name => "configure_database");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Save_Binding.Proxy'Access,
Finish_Binding.Proxy'Access,
Configure_Binding.Proxy'Access);
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "database_name" then
return Util.Beans.Objects.To_Object (From.Database.Get_Database);
elsif Name = "database_server" then
return Util.Beans.Objects.To_Object (From.Database.Get_Server);
elsif Name = "database_port" then
return Util.Beans.Objects.To_Object (From.Database.Get_Port);
elsif Name = "database_user" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user"));
elsif Name = "database_password" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password"));
end if;
if From.Changed.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name)));
end if;
declare
Param : constant String := From.Config.Get (Name);
begin
return Util.Beans.Objects.To_Object (Param);
end;
exception
when others =>
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "database_name" then
From.Database.Set_Database (Util.Beans.Objects.To_String (Value));
elsif Name = "database_server" then
From.Database.Set_Server (Util.Beans.Objects.To_String (Value));
elsif Name = "database_port" then
From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value));
elsif Name = "database_user" then
From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value));
elsif Name = "database_password" then
From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value));
elsif Name = "callback_url" then
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
From.Changed.Set ("facebook.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
From.Changed.Set ("google-plus.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
else
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Configure database");
end Configure_Database;
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Path : constant String := Ada.Strings.Unbounded.To_String (From.Path);
New_File : constant String := Path & ".tmp";
Output : Ada.Text_IO.File_Type;
procedure Read_Property (Line : in String) is
Pos : constant Natural := Util.Strings.Index (Line, '=');
begin
if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then
Ada.Text_IO.Put_Line (Output, Line);
return;
end if;
Ada.Text_IO.Put (Output, Line (Line'First .. Pos));
Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1)));
end Read_Property;
begin
Log.Info ("Saving configuration file {0}", Path);
Ada.Text_IO.Create (File => Output, Name => New_File);
Util.Files.Read_File (Path, Read_Property'Access);
Ada.Text_IO.Close (Output);
end Save;
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Finish configuration");
From.Done := True;
end Finish;
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access is
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class) is
begin
Log.Info ("Entering configuration for {0}", Config);
App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config);
begin
App.Config.Load_Properties (Config);
Util.Log.Loggers.Initialize (Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file: {0}", Config);
end;
App.Initialize (App.Config, App.Factory);
App.Set_Global ("contextPath", App.Config.Get ("contextPath"));
App.Set_Global ("setup",
Util.Beans.Objects.To_Object (App'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Add_Servlet (Name => "faces",
Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files",
Server => App.Files'Unchecked_Access);
App.Add_Mapping (Pattern => "*.html",
Name => "faces");
App.Add_Mapping (Pattern => "*.css",
Name => "files");
App.Add_Mapping (Pattern => "*.js",
Name => "files");
declare
Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P);
Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths);
begin
ASF.Applications.Main.Configs.Read_Configuration (App, Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Setup configuration file '{0}' does not exist", Path);
end;
declare
URL : constant String := App.Config.Get ("google-plus.callback_url", "");
Pos : Natural := Util.Strings.Index (URL, '#');
begin
if Pos > 0 then
App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1));
end if;
end;
App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db"));
Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access);
Server.Start;
while not App.Done loop
delay 5.0;
end loop;
end Setup;
end AWA.Setup.Applications;
|
Configure the OAuth callbacks
|
Configure the OAuth callbacks
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
576bcdfae39ec3cf92b5ece4c7c1c99c827ff8ad
|
src/security-openid.ads
|
src/security-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The OpenID manager must be declared and configured.
--
-- Mgr : Openid.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the OpenID realm and set the OpenID return callback CB. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify");
--
-- After this initialization, the OpenID manager can be used in the authentication process.
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>.
--
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The OpenID manager must be declared and configured.
--
-- Mgr : Openid.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the OpenID realm and set the OpenID return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify");
--
-- After this initialization, the OpenID manager can be used in the authentication process.
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
2f19a79a7ee81f8239eb26c14fb4a69bac485b8e
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
-- = Property Files =
-- The `Util.Properties` package and children implements support to read, write and use
-- property files either in the Java property file format or the Windows INI configuration file.
-- Each property is assigned a key and a value. The list of properties are stored in the
-- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property
-- is therefore unique in the list. Properties can be grouped together in sub-properties so
-- that a key can represent another list of properties.
--
-- == File formats ==
-- The property file consists of a simple name and value pair separated by the `=` sign.
-- Thanks to the Windows INI file format, list of properties can be grouped together
-- in sections by using the `[section-name`] notation.
--
-- test.count=20
-- test.repeat=5
-- [FileTest]
-- test.count=5
-- test.repeat=2
--
-- == Using property files ==
-- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
-- various operations that can be used. When created, the property manager is empty. One way
-- to fill it is by using the `Load_Properties` procedure to read the property file. Another
-- way is by using the `Set` procedure to insert or change a property by giving its name
-- and its value.
--
-- In this example, the property file `test.properties` is loaded and assuming that it contains
-- the above configuration example, the `Get ("test.count")` will return the string `"20"`.
--
-- with Util.Properties;
-- ...
-- Props : Util.Properties.Manager;
-- ...
-- Props.Load_Properties (Path => "test.properties");
-- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
-- Props.Set ("test.repeat", "23");
-- Props.Save_Properties (Path => "test.properties");
--
-- To be able to access a section from the property manager, it is necessary to retrieve it
-- by using the `Get` function and giving the section name. For example, to retrieve the
-- `test.count` property of the `FileTest` section, the following code is used:
--
-- FileTest : Util.Properties.Manager := Props.Get ("FileTest");
-- ...
-- Ada.Text_IO.Put_Line ("[FileTest] Count: " & FileTest.Get ("test.count");
--
-- @include util-properties-json.ads
-- @include util-properties-bundles.ads
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Document the properties framework
|
Document the properties framework
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a0103802f449302cace4b70f73ed2dfef2013d54
|
regtests/babel-base-users-tests.adb
|
regtests/babel-base-users-tests.adb
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- 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.Test_Caller;
package body Babel.Base.Users.Tests is
use type Babel.Uid_Type;
use type Babel.Gid_Type;
use type Util.Strings.Name_Access;
package Caller is new Util.Test_Caller (Test, "Base.Users");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Base.Users.Find",
Test_Find'Access);
Caller.Add_Test (Suite, "Test Babel.Base.Users.Get_Name",
Test_Get_Name'Access);
end Add_Tests;
-- ------------------------------
-- Test the Find function resolving some existing user.
-- ------------------------------
procedure Test_Find (T : in out Test) is
Db : Babel.Base.Users.Database;
User : User_Type;
begin
User := Db.Find (0, 0);
T.Assert (User.Name /= null, "User uid=0 was not found");
T.Assert (User.Group /= null, "User gid=0 was not found");
Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name");
Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name");
User := Db.Find ("bin", "daemon");
T.Assert (User.Name /= null, "User bin was not found");
T.Assert (User.Group /= null, "Group daemon was not found");
Util.Tests.Assert_Equals (T, "bin", User.Name.all, "Invalid 'bin' user name");
Util.Tests.Assert_Equals (T, "daemon", User.Group.all, "Invalid 'daemon' group name");
T.Assert (User.Uid > 0, "Invalid 'bin' uid");
T.Assert (User.Gid > 0, "Invalid 'daemon' gid");
end Test_Find;
-- ------------------------------
-- Test the Get_Name operation.
-- ------------------------------
procedure Test_Get_Name (T : in out Test) is
Name : Name_Access;
Db : Database;
begin
Name := Db.Get_Name (0);
T.Assert (Name /= null, "Get_Name (0) returned null");
Util.Tests.Assert_Equals (T, "root", Name.all, "Invalid name returned for Get_Name (0)");
Name := Db.Get_Name (1);
T.Assert (Name /= null, "Get_Name (1) returned null");
Name := Db.Get_Name (55555);
T.Assert (Name = null, "Get_Name (55555) returned a non null name");
end Test_Get_Name;
end Babel.Base.Users.Tests;
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- 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.Test_Caller;
package body Babel.Base.Users.Tests is
use type Babel.Uid_Type;
use type Babel.Gid_Type;
use type Util.Strings.Name_Access;
package Caller is new Util.Test_Caller (Test, "Base.Users");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Base.Users.Find",
Test_Find'Access);
Caller.Add_Test (Suite, "Test Babel.Base.Users.Get_Name",
Test_Get_Name'Access);
Caller.Add_Test (Suite, "Test Babel.Base.Users.Get_Uid",
Test_Get_Uid'Access);
end Add_Tests;
-- ------------------------------
-- Test the Find function resolving some existing user.
-- ------------------------------
procedure Test_Find (T : in out Test) is
Db : Babel.Base.Users.Database;
User : User_Type;
begin
User := Db.Find (0, 0);
T.Assert (User.Name /= null, "User uid=0 was not found");
T.Assert (User.Group /= null, "User gid=0 was not found");
Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name");
Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name");
User := Db.Find ("bin", "daemon");
T.Assert (User.Name /= null, "User bin was not found");
T.Assert (User.Group /= null, "Group daemon was not found");
Util.Tests.Assert_Equals (T, "bin", User.Name.all, "Invalid 'bin' user name");
Util.Tests.Assert_Equals (T, "daemon", User.Group.all, "Invalid 'daemon' group name");
T.Assert (User.Uid > 0, "Invalid 'bin' uid");
T.Assert (User.Gid > 0, "Invalid 'daemon' gid");
end Test_Find;
-- ------------------------------
-- Test the Get_Name operation.
-- ------------------------------
procedure Test_Get_Name (T : in out Test) is
Name : Name_Access;
Db : Database;
begin
Name := Db.Get_Name (0);
T.Assert (Name /= null, "Get_Name (0) returned null");
Util.Tests.Assert_Equals (T, "root", Name.all, "Invalid name returned for Get_Name (0)");
Name := Db.Get_Name (1);
T.Assert (Name /= null, "Get_Name (1) returned null");
Name := Db.Get_Name (55555);
T.Assert (Name = null, "Get_Name (55555) returned a non null name");
end Test_Get_Name;
-- ------------------------------
-- Test the Get_Uid operation.
-- ------------------------------
procedure Test_Get_Uid (T : in out Test) is
Db : Database;
Uid : Uid_Type;
begin
Uid := Db.Get_Uid ("root");
Util.Tests.Assert_Equals (T, 0, Natural (Uid), "Get_Uid (root) returned invalid uid");
Uid := Db.Get_Uid ("admin");
T.Assert (Uid /= 0, "Get_Uid (admin) returned invalid uid");
Uid := Db.Get_Uid ("Katniss");
T.Assert (Uid /= 0, "Get_Uid (Katniss) returned invalid uid");
end Test_Get_Uid;
end Babel.Base.Users.Tests;
|
Implement the Test_Get_Uid procedure and add a new test case to check the Get_Uid operation
|
Implement the Test_Get_Uid procedure and add a new test case to check the Get_Uid operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
9a4d6427b0504f6e3f95bcbcbadcbc1e41162f30
|
src/asf-applications-main-configs.adb
|
src/asf-applications-main-configs.adb
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with EL.Functions.Namespaces;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Servlets.Faces.Mappers;
with ASF.Beans.Mappers;
with ASF.Views.Nodes.Core;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale;
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is
Name : constant String := Util.Beans.Objects.To_String (Value);
Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name);
begin
return Locale;
end Get_Locale;
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
when TAG_DEFAULT_LOCALE =>
N.App.Set_Default_Locale (Get_Locale (Value));
when TAG_SUPPORTED_LOCALE =>
N.App.Add_Supported_Locale (Get_Locale (Value));
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
procedure Set_Property_Context (Params : in Util.Properties.Manager'Class);
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantiation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
package Faces_Config is
new ASF.Servlets.Faces.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Faces_Config);
Config : aliased Application_Config;
NS_Mapper : aliased EL.Functions.Namespaces.NS_Function_Mapper;
procedure Set_Property_Context (Params : in Util.Properties.Manager'Class) is
begin
Prop_Context.Set_Properties (Params);
end Set_Property_Context;
begin
-- Install the property context that gives access
-- to the application configuration properties
App.Get_Init_Parameters (Set_Property_Context'Access);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
-- Setup the function mapper to resolve uses of functions within EL expressions.
NS_Mapper.Set_Namespace (Prefix => "fn",
URI => ASF.Views.Nodes.Core.FN_URI);
NS_Mapper.Set_Function_Mapper (App.Functions'Unchecked_Access);
Context.Set_Function_Mapper (NS_Mapper'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Servlet_Config.Config.Override_Context := Override_Context;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE);
AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE);
end ASF.Applications.Main.Configs;
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with EL.Functions.Namespaces;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Servlets.Faces.Mappers;
with ASF.Beans.Mappers;
with ASF.Views.Nodes.Core;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale;
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is
Name : constant String := Util.Beans.Objects.To_String (Value);
Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name);
begin
return Locale;
end Get_Locale;
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
when TAG_DEFAULT_LOCALE =>
N.App.Set_Default_Locale (Get_Locale (Value));
when TAG_SUPPORTED_LOCALE =>
N.App.Add_Supported_Locale (Get_Locale (Value));
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
procedure Set_Property_Context (Params : in Util.Properties.Manager'Class);
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantiation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Mapper, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Mapper, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Mapper, App.all'Access,
Context.all'Access);
package Faces_Config is
new ASF.Servlets.Faces.Mappers.Reader_Config (Mapper, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Faces_Config);
Config : aliased Application_Config;
NS_Mapper : aliased EL.Functions.Namespaces.NS_Function_Mapper;
procedure Set_Property_Context (Params : in Util.Properties.Manager'Class) is
begin
Prop_Context.Set_Properties (Params);
end Set_Property_Context;
begin
-- Install the property context that gives access
-- to the application configuration properties
App.Get_Init_Parameters (Set_Property_Context'Access);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
-- Setup the function mapper to resolve uses of functions within EL expressions.
NS_Mapper.Set_Namespace (Prefix => "fn",
URI => ASF.Views.Nodes.Core.FN_URI);
NS_Mapper.Set_Function_Mapper (App.Functions'Unchecked_Access);
Context.Set_Function_Mapper (NS_Mapper'Unchecked_Access);
Mapper.Add_Mapping ("faces-config", AMapper'Access);
Mapper.Add_Mapping ("module", AMapper'Access);
Mapper.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Servlet_Config.Config.Override_Context := Override_Context;
Application_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Mapper, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File, Mapper);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE);
AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE);
end ASF.Applications.Main.Configs;
|
Update the Reader_Config to use the new parser/mapper interface
|
Update the Reader_Config to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
01f08d57b35efcb07640a83cc2d8fb68314e8acb
|
src/asf-components-widgets-inputs.ads
|
src/asf-components-widgets-inputs.ads
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Beans.Basic;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
package ASF.Components.Widgets.Inputs is
use ASF.Contexts.Faces;
use ASF.Contexts.Writer;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <dl class='... awa-error'>
-- <dt>title <i>required</i></dt>
-- <dd><input type='text' ...> <em/>
-- <span class='...'>message</span>
-- </dd>
-- </dl>
type UIInput is new ASF.Components.Html.Forms.UIInput with null record;
type UIInput_Access is access all UIInput'Class;
-- Render the input field title.
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class);
-- ------------------------------
-- The auto complete component.
-- ------------------------------
--
type UIComplete is new UIInput with private;
type UIComplete_Access is access all UIInput'Class;
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class);
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class);
private
type UIComplete is new UIInput with record
Match_Value : Util.Beans.Objects.Object;
end record;
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
package ASF.Components.Widgets.Inputs is
use ASF.Contexts.Faces;
use ASF.Contexts.Writer;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <dl class='... awa-error'>
-- <dt>title <i>required</i></dt>
-- <dd><input type='text' ...> <em/>
-- <span class='...'>message</span>
-- </dd>
-- </dl>
type UIInput is new ASF.Components.Html.Forms.UIInput with null record;
type UIInput_Access is access all UIInput'Class;
-- Render the input field title.
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class);
-- ------------------------------
-- The auto complete component.
-- ------------------------------
--
type UIComplete is new UIInput with private;
type UIComplete_Access is access all UIInput'Class;
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class);
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class);
-- ------------------------------
-- The input date component.
-- ------------------------------
--
type UIInputDate is new UIInput with null record;
type UIInputDate_Access is access all UIInputDate'Class;
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIInputDate;
Context : in out Faces_Context'Class);
private
type UIComplete is new UIInput with record
Match_Value : Util.Beans.Objects.Object;
end record;
end ASF.Components.Widgets.Inputs;
|
Declare the inputDate component
|
Declare the inputDate component
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
161122fef8ce1ffa558e4bc3a8efd89aef21ea18
|
src/asf-components-html-selects.adb
|
src/asf-components-html-selects.adb
|
-----------------------------------------------------------------------
-- html-selects -- ASF HTML UISelectOne and UISelectMany components
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Utils;
package body ASF.Components.Html.Selects is
-- ------------------------------
-- UISelectItem Component
-- ------------------------------
ITEM_LABEL_NAME : constant String := "itemLabel";
ITEM_VALUE_NAME : constant String := "itemValue";
ITEM_DESCRIPTION_NAME : constant String := "itemDescription";
ITEM_DISABLED_NAME : constant String := "itemDisabled";
SELECT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Iterator over the Select_Item elements
-- ------------------------------
-- ------------------------------
-- Get an iterator to scan the component children.
-- ------------------------------
procedure First (UI : in UISelectOne'Class;
Context : in Faces_Context'Class;
Iterator : out Cursor) is
begin
Iterator.Component := UI.First;
Iterator.Pos := 0;
Iterator.Last := 0;
while ASF.Components.Base.Has_Element (Iterator.Component) loop
Iterator.Current := ASF.Components.Base.Element (Iterator.Component);
if Iterator.Current.all in UISelectItem'Class then
return;
end if;
if Iterator.Current.all in UISelectItems'Class then
Iterator.List := UISelectItems'Class (Iterator.Current.all)
.Get_Select_Item_List (Context);
Iterator.Last := Iterator.List.Length;
Iterator.Pos := 1;
if Iterator.Last > 0 then
return;
end if;
end if;
ASF.Components.Base.Next (Iterator.Component);
end loop;
Iterator.Pos := 0;
Iterator.Current := null;
end First;
-- ------------------------------
-- Returns True if the iterator points to a valid child.
-- ------------------------------
function Has_Element (Pos : in Cursor) return Boolean is
use type ASF.Components.Base.UIComponent_Access;
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return True;
else
return Pos.Current /= null;
end if;
end Has_Element;
-- ------------------------------
-- Get the child component pointed to by the iterator.
-- ------------------------------
function Element (Pos : in Cursor;
Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return Pos.List.Get_Select_Item (Pos.Pos);
else
return UISelectItem'Class (Pos.Current.all).Get_Select_Item (Context);
end if;
end Element;
-- ------------------------------
-- Move to the next child.
-- ------------------------------
procedure Next (Pos : in out Cursor;
Context : in Faces_Context'Class) is
begin
if Pos.Pos > 0 and Pos.Pos < Pos.Last then
Pos.Pos := Pos.Pos + 1;
else
Pos.Pos := 0;
loop
Pos.Current := null;
ASF.Components.Base.Next (Pos.Component);
exit when not ASF.Components.Base.Has_Element (Pos.Component);
Pos.Current := ASF.Components.Base.Element (Pos.Component);
exit when Pos.Current.all in UISelectItem'Class;
if Pos.Current.all in UISelectItems'Class then
Pos.List := UISelectItems'Class (Pos.Current.all).Get_Select_Item_List (Context);
Pos.Last := Pos.List.Length;
Pos.Pos := 1;
exit when Pos.Last > 0;
Pos.Pos := 0;
end if;
end loop;
end if;
end Next;
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item (From : in UISelectItem;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item is
use Util.Beans.Objects;
Val : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
if not Is_Null (Val) then
return ASF.Models.Selects.To_Select_Item (Val);
end if;
declare
Label : constant Object := From.Get_Attribute (Name => ITEM_LABEL_NAME,
Context => Context);
Value : constant Object := From.Get_Attribute (Name => ITEM_VALUE_NAME,
Context => Context);
Description : constant Object := From.Get_Attribute (Name => ITEM_DESCRIPTION_NAME,
Context => Context);
Disabled : constant Boolean := From.Get_Attribute (Name => ITEM_DISABLED_NAME,
Context => Context);
begin
return ASF.Models.Selects.Create_Select_Item (Label, Value, Description, Disabled);
end;
end Get_Select_Item;
-- ------------------------------
-- UISelectItems Component
-- ------------------------------
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item_List (From : in UISelectItems;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item_List is
use Util.Beans.Objects;
Value : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
return ASF.Models.Selects.To_Select_Item_List (Value);
end Get_Select_Item_List;
-- ------------------------------
-- SelectOne Component
-- ------------------------------
-- ------------------------------
-- Render the <b>select</b> element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UISelectOne'Class (UI).Render_Select (Context);
end if;
end Encode_Begin;
-- ------------------------------
-- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if
-- the component is rendered.
-- ------------------------------
procedure Render_Select (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value;
begin
Writer.Start_Element ("select");
Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id);
UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer);
UISelectOne'Class (UI).Render_Options (Value, Context);
Writer.End_Element ("select");
end Render_Select;
-- ------------------------------
-- Renders the <b>option</b> element. This is called by <b>Render_Select</b> to
-- generate the component options.
-- ------------------------------
procedure Render_Options (UI : in UISelectOne;
Value : in Util.Beans.Objects.Object;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value);
Iter : Cursor;
begin
UI.First (Context, Iter);
while Has_Element (Iter) loop
declare
Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context);
Item_Value : constant Wide_Wide_String := Item.Get_Value;
begin
Writer.Start_Element ("option");
Writer.Write_Wide_Attribute ("value", Item_Value);
if Item_Value = Selected then
Writer.Write_Attribute ("selected", "selected");
end if;
if Item.Is_Escaped then
Writer.Write_Wide_Text (Item.Get_Label);
else
Writer.Write_Wide_Text (Item.Get_Label);
end if;
Writer.End_Element ("option");
Next (Iter, Context);
end;
end loop;
end Render_Options;
begin
ASF.Utils.Set_Text_Attributes (SELECT_ATTRIBUTE_NAMES);
ASF.Utils.Set_Interactive_Attributes (SELECT_ATTRIBUTE_NAMES);
end ASF.Components.Html.Selects;
|
-----------------------------------------------------------------------
-- html-selects -- ASF HTML UISelectOne and UISelectMany components
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Utils;
package body ASF.Components.Html.Selects is
-- ------------------------------
-- UISelectItem Component
-- ------------------------------
ITEM_LABEL_NAME : constant String := "itemLabel";
ITEM_VALUE_NAME : constant String := "itemValue";
ITEM_DESCRIPTION_NAME : constant String := "itemDescription";
ITEM_DISABLED_NAME : constant String := "itemDisabled";
SELECT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Iterator over the Select_Item elements
-- ------------------------------
-- ------------------------------
-- Get an iterator to scan the component children.
-- ------------------------------
procedure First (UI : in UISelectOne'Class;
Context : in Faces_Context'Class;
Iterator : out Cursor) is
begin
Iterator.Component := UI.First;
Iterator.Pos := 0;
Iterator.Last := 0;
while ASF.Components.Base.Has_Element (Iterator.Component) loop
Iterator.Current := ASF.Components.Base.Element (Iterator.Component);
if Iterator.Current.all in UISelectItem'Class then
return;
end if;
if Iterator.Current.all in UISelectItems'Class then
Iterator.List := UISelectItems'Class (Iterator.Current.all)
.Get_Select_Item_List (Context);
Iterator.Last := Iterator.List.Length;
Iterator.Pos := 1;
if Iterator.Last > 0 then
return;
end if;
end if;
ASF.Components.Base.Next (Iterator.Component);
end loop;
Iterator.Pos := 0;
Iterator.Current := null;
end First;
-- ------------------------------
-- Returns True if the iterator points to a valid child.
-- ------------------------------
function Has_Element (Pos : in Cursor) return Boolean is
use type ASF.Components.Base.UIComponent_Access;
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return True;
else
return Pos.Current /= null;
end if;
end Has_Element;
-- ------------------------------
-- Get the child component pointed to by the iterator.
-- ------------------------------
function Element (Pos : in Cursor;
Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return Pos.List.Get_Select_Item (Pos.Pos);
else
return UISelectItem'Class (Pos.Current.all).Get_Select_Item (Context);
end if;
end Element;
-- ------------------------------
-- Move to the next child.
-- ------------------------------
procedure Next (Pos : in out Cursor;
Context : in Faces_Context'Class) is
begin
if Pos.Pos > 0 and Pos.Pos < Pos.Last then
Pos.Pos := Pos.Pos + 1;
else
Pos.Pos := 0;
loop
Pos.Current := null;
ASF.Components.Base.Next (Pos.Component);
exit when not ASF.Components.Base.Has_Element (Pos.Component);
Pos.Current := ASF.Components.Base.Element (Pos.Component);
exit when Pos.Current.all in UISelectItem'Class;
if Pos.Current.all in UISelectItems'Class then
Pos.List := UISelectItems'Class (Pos.Current.all).Get_Select_Item_List (Context);
Pos.Last := Pos.List.Length;
Pos.Pos := 1;
exit when Pos.Last > 0;
Pos.Pos := 0;
end if;
end loop;
end if;
end Next;
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item (From : in UISelectItem;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item is
use Util.Beans.Objects;
Val : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
if not Is_Null (Val) then
return ASF.Models.Selects.To_Select_Item (Val);
end if;
declare
Label : constant Object := From.Get_Attribute (Name => ITEM_LABEL_NAME,
Context => Context);
Value : constant Object := From.Get_Attribute (Name => ITEM_VALUE_NAME,
Context => Context);
Description : constant Object := From.Get_Attribute (Name => ITEM_DESCRIPTION_NAME,
Context => Context);
Disabled : constant Boolean := From.Get_Attribute (Name => ITEM_DISABLED_NAME,
Context => Context);
begin
if Is_Null (Label) then
return ASF.Models.Selects.Create_Select_Item (Value, Value, Description, Disabled);
else
return ASF.Models.Selects.Create_Select_Item (Label, Value, Description, Disabled);
end if;
end;
end Get_Select_Item;
-- ------------------------------
-- UISelectItems Component
-- ------------------------------
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item_List (From : in UISelectItems;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item_List is
use Util.Beans.Objects;
Value : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
return ASF.Models.Selects.To_Select_Item_List (Value);
end Get_Select_Item_List;
-- ------------------------------
-- SelectOne Component
-- ------------------------------
-- ------------------------------
-- Render the <b>select</b> element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UISelectOne'Class (UI).Render_Select (Context);
end if;
end Encode_Begin;
-- ------------------------------
-- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if
-- the component is rendered.
-- ------------------------------
procedure Render_Select (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value;
begin
Writer.Start_Element ("select");
Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id);
UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer);
UISelectOne'Class (UI).Render_Options (Value, Context);
Writer.End_Element ("select");
end Render_Select;
-- ------------------------------
-- Renders the <b>option</b> element. This is called by <b>Render_Select</b> to
-- generate the component options.
-- ------------------------------
procedure Render_Options (UI : in UISelectOne;
Value : in Util.Beans.Objects.Object;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value);
Iter : Cursor;
begin
UI.First (Context, Iter);
while Has_Element (Iter) loop
declare
Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context);
Item_Value : constant Wide_Wide_String := Item.Get_Value;
begin
Writer.Start_Element ("option");
Writer.Write_Wide_Attribute ("value", Item_Value);
if Item_Value = Selected then
Writer.Write_Attribute ("selected", "selected");
end if;
if Item.Is_Escaped then
Writer.Write_Wide_Text (Item.Get_Label);
else
Writer.Write_Wide_Text (Item.Get_Label);
end if;
Writer.End_Element ("option");
Next (Iter, Context);
end;
end loop;
end Render_Options;
begin
ASF.Utils.Set_Text_Attributes (SELECT_ATTRIBUTE_NAMES);
ASF.Utils.Set_Interactive_Attributes (SELECT_ATTRIBUTE_NAMES);
end ASF.Components.Html.Selects;
|
Use the select item value as label if the label is not specified
|
Use the select item value as label if the label is not specified
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
4d56983099ca796a057919894384bc3351cfd882
|
src/asf-navigations.adb
|
src/asf-navigations.adb
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Rule) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class,
Navigation_Access);
begin
while not Controller.Navigators.Is_Empty loop
declare
Iter : Navigator_Vector.Cursor := Controller.Navigators.Last;
Navigator : Navigation_Access := Navigator_Vector.Element (Iter);
begin
Free (Navigator.Outcome);
Free (Navigator.Action);
Free (Navigator);
Controller.Navigators.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Navigation_Rules) is
procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access);
begin
while not Controller.Rules.Is_Empty loop
declare
Iter : Rule_Map.Cursor := Controller.Rules.First;
Rule : Rule_Access := Rule_Map.Element (Iter);
begin
Rule.Clear;
Free (Rule);
Controller.Rules.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- Provide a default navigation rules for the view and the outcome when no application
-- navigation was found. The default looks for an XHTML file in the same directory as
-- the view and which has the base name defined by <b>Outcome</b>.
-- ------------------------------
procedure Handle_Default_Navigation (Handler : in Navigation_Handler;
View : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Pos : constant Natural := Util.Strings.Rindex (View, '/');
Root : Components.Root.UIViewRoot;
View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler;
begin
if View_Handler = null then
View_Handler := Handler.Application.Get_View_Handler;
end if;
if Pos > 0 then
declare
Name : constant String := View (View'First .. Pos) & Outcome;
begin
Log.Debug ("Using default navigatation from view {0} to {1}", View, Name);
View_Handler.Create_View (Name, Context, Root);
end;
else
Log.Debug ("Using default navigatation from view {0} to {1}", View, View);
View_Handler.Create_View (Outcome, Context, Root);
end if;
-- If the 'outcome' refers to a real view, use it. Otherwise keep the current view.
if Components.Root.Get_Root (Root) /= null then
Context.Set_View_Root (Root);
end if;
exception
when others =>
Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}",
View, Outcome);
raise;
end Handle_Default_Navigation;
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access;
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := N - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
else
Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}",
Name, Action, Outcome);
Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access);
begin
if Handler.Rules /= null then
Clear (Handler.Rules.all);
Free (Handler.Rules);
end if;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition);
end Add_Navigation_Case;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- by using the navigation rule defined by <b>Navigator</b>.
-- Some optional conditions are evaluated:
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class;
Navigator : in Navigation_Access;
From : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
pragma Unreferenced (Condition);
begin
Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome);
if Outcome'Length > 0 then
Navigator.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
Navigator.Action := new String '(Action);
end if;
if Handler.View_Handler = null then
Handler.View_Handler := Handler.Application.Get_View_Handler;
end if;
Navigator.View_Handler := Handler.View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (Navigator);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Rule) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class,
Navigation_Access);
begin
while not Controller.Navigators.Is_Empty loop
declare
Iter : Navigator_Vector.Cursor := Controller.Navigators.Last;
Navigator : Navigation_Access := Navigator_Vector.Element (Iter);
begin
Free (Navigator.Outcome);
Free (Navigator.Action);
Free (Navigator);
Controller.Navigators.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Navigation_Rules) is
procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access);
begin
while not Controller.Rules.Is_Empty loop
declare
Iter : Rule_Map.Cursor := Controller.Rules.First;
Rule : Rule_Access := Rule_Map.Element (Iter);
begin
Rule.Clear;
Free (Rule);
Controller.Rules.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- Provide a default navigation rules for the view and the outcome when no application
-- navigation was found. The default looks for an XHTML file in the same directory as
-- the view and which has the base name defined by <b>Outcome</b>.
-- ------------------------------
procedure Handle_Default_Navigation (Handler : in Navigation_Handler;
View : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Pos : constant Natural := Util.Strings.Rindex (View, '/');
Root : Components.Root.UIViewRoot;
View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler;
begin
if View_Handler = null then
View_Handler := Handler.Application.Get_View_Handler;
end if;
if Pos > 0 then
declare
Name : constant String := View (View'First .. Pos) & Outcome;
begin
Log.Debug ("Using default navigation from view {0} to {1}", View, Name);
View_Handler.Create_View (Name, Context, Root);
end;
else
Log.Debug ("Using default navigation from view {0} to {1}", View, View);
View_Handler.Create_View (Outcome, Context, Root);
end if;
-- If the 'outcome' refers to a real view, use it. Otherwise keep the current view.
if Components.Root.Get_Root (Root) /= null then
Context.Set_View_Root (Root);
end if;
exception
when others =>
Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}",
View, Outcome);
raise;
end Handle_Default_Navigation;
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access;
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := N - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
else
Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}",
Name, Action, Outcome);
Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access);
begin
if Handler.Rules /= null then
Clear (Handler.Rules.all);
Free (Handler.Rules);
end if;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition);
end Add_Navigation_Case;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- by using the navigation rule defined by <b>Navigator</b>.
-- Some optional conditions are evaluated:
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class;
Navigator : in Navigation_Access;
From : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
pragma Unreferenced (Condition);
begin
Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome);
if Outcome'Length > 0 then
Navigator.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
Navigator.Action := new String '(Action);
end if;
if Handler.View_Handler = null then
Handler.View_Handler := Handler.Application.Get_View_Handler;
end if;
Navigator.View_Handler := Handler.View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (Navigator);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
Fix log messages in navigation rules.
|
Fix log messages in navigation rules.
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
c3bbc782c2225c59f06a4092d9daad7af61d2290
|
regtests/util-texts-builders_tests.adb
|
regtests/util-texts-builders_tests.adb
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Util.Test_Caller;
with Util.Texts.Builders;
with Util.Measures;
package body Util.Texts.Builders_Tests is
package String_Builder is new Util.Texts.Builders (Element_Type => Character,
Input => String,
Chunk_Size => 100);
package Caller is new Util.Test_Caller (Test, "Texts.Builders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length",
Test_Length'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append",
Test_Append'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear",
Test_Clear'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate",
Test_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Iterate",
Test_Inline_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail",
Test_Tail'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf",
Test_Perf'Access);
end Add_Tests;
-- ------------------------------
-- Test the length operation.
-- ------------------------------
procedure Test_Length (T : in out Test) is
B : String_Builder.Builder (10);
begin
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity");
end Test_Length;
-- ------------------------------
-- Test the append operation.
-- ------------------------------
procedure Test_Append (T : in out Test) is
S : constant String := "0123456789";
B : String_Builder.Builder (3);
begin
String_Builder.Append (B, "a string");
Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
-- Append new string and check content.
String_Builder.Append (B, " b string");
Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B),
"Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
for I in S'Range loop
String_Builder.Append (B, S (I));
end loop;
Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append");
end Test_Append;
-- ------------------------------
-- Test the clear operation.
-- ------------------------------
procedure Test_Clear (T : in out Test) is
B : String_Builder.Builder (7);
begin
for I in 1 .. 10 loop
String_Builder.Append (B, "a string");
end loop;
Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear");
Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear");
end Test_Clear;
-- ------------------------------
-- Test the tail operation.
-- ------------------------------
procedure Test_Tail (T : in out Test) is
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural);
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural) is
P : constant String := "0123456789";
B : String_Builder.Builder (Min);
begin
for I in 1 .. Max loop
String_Builder.Append (B, P (1 + (I mod 10)));
end loop;
declare
S : constant String := String_Builder.Tail (B, L);
S2 : constant String := String_Builder.To_Array (B);
begin
Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length");
if L >= Max then
Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result");
else
Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S,
"Invalid Tail result {"
& Positive'Image (Min) & ","
& Positive'Image (Max) & ","
& Positive'Image (L) & "]");
end if;
end;
end Check_Tail;
begin
for I in 1 .. 100 loop
for J in 1 .. 8 loop
for K in 1 .. I + 3 loop
Check_Tail (J, I, K);
end loop;
end loop;
end loop;
end Test_Tail;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
String_Builder.Iterate (B, Process'Access);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Iterate;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Inline_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
procedure Get is new String_Builder.Inline_Iterate (Process);
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
Get (B);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Inline_Iterate;
-- ------------------------------
-- Test the append and iterate performance.
-- ------------------------------
procedure Test_Perf (T : in out Test) is
Perf : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string-append.csv"));
Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time");
for Block_Size in 1 .. 300 loop
declare
B : String_Builder.Builder (10);
N : constant String := Natural'Image (Block_Size * 10) & ",";
begin
String_Builder.Set_Block_Size (B, Block_Size * 10);
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
end;
declare
S : Util.Measures.Stamp;
R : constant String := String_Builder.To_Array (B);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (R'Length > 0, "Invalid string length");
end;
declare
Count : Natural := 0;
procedure Process (Item : in String);
procedure Process (Item : in String) is
pragma Unreferenced (Item);
begin
Count := Count + 1;
end Process;
S : Util.Measures.Stamp;
begin
String_Builder.Iterate (B, Process'Access);
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (Count > 0, "The string builder was empty");
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
Ada.Text_IO.Close (Perf);
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string.csv"));
Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512),"
& "Append (1024),Unbounded,Iterate Time");
for I in 1 .. 4000 loop
declare
N : constant String := Natural'Image (I) & ",";
B : String_Builder.Builder (10);
B2 : String_Builder.Builder (10);
B3 : String_Builder.Builder (10);
U : Ada.Strings.Unbounded.Unbounded_String;
S : Util.Measures.Stamp;
begin
for J in 1 .. I loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B2, 512);
for J in 1 .. I loop
String_Builder.Append (B2, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B3, 1024);
for J in 1 .. I loop
String_Builder.Append (B3, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
for J in 1 .. I loop
Ada.Strings.Unbounded.Append (U, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
declare
R : constant String := String_Builder.To_Array (B);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
declare
R : constant String := Ada.Strings.Unbounded.To_String (U);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
end Test_Perf;
end Util.Texts.Builders_Tests;
|
-----------------------------------------------------------------------
-- util-texts-builders_tests -- Unit tests for text builders
-- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Util.Test_Caller;
with Util.Texts.Builders;
with Util.Measures;
package body Util.Texts.Builders_Tests is
package String_Builder is new Util.Texts.Builders (Element_Type => Character,
Input => String,
Chunk_Size => 100);
package Caller is new Util.Test_Caller (Test, "Texts.Builders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length",
Test_Length'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append",
Test_Append'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Append",
Test_Inline_Append'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear",
Test_Clear'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate",
Test_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Iterate",
Test_Inline_Iterate'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail",
Test_Tail'Access);
Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf",
Test_Perf'Access);
end Add_Tests;
-- ------------------------------
-- Test the length operation.
-- ------------------------------
procedure Test_Length (T : in out Test) is
B : String_Builder.Builder (10);
begin
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity");
end Test_Length;
-- ------------------------------
-- Test the append operation.
-- ------------------------------
procedure Test_Append (T : in out Test) is
S : constant String := "0123456789";
B : String_Builder.Builder (3);
begin
String_Builder.Append (B, "a string");
Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
-- Append new string and check content.
String_Builder.Append (B, " b string");
Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B),
"Invalid content");
Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
for I in S'Range loop
String_Builder.Append (B, S (I));
end loop;
Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append");
end Test_Append;
-- ------------------------------
-- Test the append operation.
-- ------------------------------
procedure Test_Inline_Append (T : in out Test) is
procedure Append (Into : in out String;
Last : out Natural);
S : constant String := "0123456789";
I : Positive := S'First;
B : String_Builder.Builder (3);
procedure Append (Into : in out String;
Last : out Natural) is
Pos : Natural := Into'First;
begin
while Pos <= Into'Last and I <= S'Last loop
Into (Pos) := S (I);
Pos := Pos + 1;
I := I + 1;
end loop;
Last := Pos - 1;
end Append;
procedure Fill is new String_Builder.Inline_Append (Append);
begin
Fill (B);
Util.Tests.Assert_Equals (T, S'Length, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, "0123456789", String_Builder.To_Array (B), "Invalid content");
I := S'First;
Fill (B);
Util.Tests.Assert_Equals (T, "01234567890123456789",
String_Builder.To_Array (B), "Invalid content");
String_Builder.Clear (B);
I := S'Last;
Fill (B);
Util.Tests.Assert_Equals (T, "9", String_Builder.To_Array (B), "Invalid content");
String_Builder.Clear (B);
I := S'Last + 1;
Fill (B);
Util.Tests.Assert_Equals (T, "", String_Builder.To_Array (B), "Invalid content");
end Test_Inline_Append;
-- ------------------------------
-- Test the clear operation.
-- ------------------------------
procedure Test_Clear (T : in out Test) is
B : String_Builder.Builder (7);
begin
for I in 1 .. 10 loop
String_Builder.Append (B, "a string");
end loop;
Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length");
Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity");
String_Builder.Clear (B);
Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear");
Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear");
end Test_Clear;
-- ------------------------------
-- Test the tail operation.
-- ------------------------------
procedure Test_Tail (T : in out Test) is
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural);
procedure Check_Tail (Min : in Positive;
Max : in Positive;
L : in Natural) is
P : constant String := "0123456789";
B : String_Builder.Builder (Min);
begin
for I in 1 .. Max loop
String_Builder.Append (B, P (1 + (I mod 10)));
end loop;
declare
S : constant String := String_Builder.Tail (B, L);
S2 : constant String := String_Builder.To_Array (B);
begin
Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length");
if L >= Max then
Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result");
else
Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S,
"Invalid Tail result {"
& Positive'Image (Min) & ","
& Positive'Image (Max) & ","
& Positive'Image (L) & "]");
end if;
end;
end Check_Tail;
begin
for I in 1 .. 100 loop
for J in 1 .. 8 loop
for K in 1 .. I + 3 loop
Check_Tail (J, I, K);
end loop;
end loop;
end loop;
end Test_Tail;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
String_Builder.Iterate (B, Process'Access);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Iterate;
-- ------------------------------
-- Test the iterate operation.
-- ------------------------------
procedure Test_Inline_Iterate (T : in out Test) is
procedure Process (S : in String);
B : String_Builder.Builder (13);
R : Ada.Strings.Unbounded.Unbounded_String;
procedure Process (S : in String) is
begin
Ada.Strings.Unbounded.Append (R, S);
end Process;
procedure Get is new String_Builder.Inline_Iterate (Process);
begin
for I in 1 .. 100 loop
String_Builder.Append (B, "The Iterate procedure avoids the string copy "
& "on the secondary stack");
end loop;
Get (B);
Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R),
"Invalid length in iterate string");
Util.Tests.Assert_Equals (T, String_Builder.To_Array (B),
Ada.Strings.Unbounded.To_String (R), "Invalid Iterate");
end Test_Inline_Iterate;
-- ------------------------------
-- Test the append and iterate performance.
-- ------------------------------
procedure Test_Perf (T : in out Test) is
Perf : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string-append.csv"));
Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time");
for Block_Size in 1 .. 300 loop
declare
B : String_Builder.Builder (10);
N : constant String := Natural'Image (Block_Size * 10) & ",";
begin
String_Builder.Set_Block_Size (B, Block_Size * 10);
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
end;
declare
S : Util.Measures.Stamp;
R : constant String := String_Builder.To_Array (B);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (R'Length > 0, "Invalid string length");
end;
declare
Count : Natural := 0;
procedure Process (Item : in String);
procedure Process (Item : in String) is
pragma Unreferenced (Item);
begin
Count := Count + 1;
end Process;
S : Util.Measures.Stamp;
begin
String_Builder.Iterate (B, Process'Access);
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
T.Assert (Count > 0, "The string builder was empty");
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
Ada.Text_IO.Close (Perf);
Ada.Text_IO.Create (File => Perf,
Name => Util.Tests.Get_Test_Path ("string.csv"));
Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512),"
& "Append (1024),Unbounded,Iterate Time");
for I in 1 .. 4000 loop
declare
N : constant String := Natural'Image (I) & ",";
B : String_Builder.Builder (10);
B2 : String_Builder.Builder (10);
B3 : String_Builder.Builder (10);
U : Ada.Strings.Unbounded.Unbounded_String;
S : Util.Measures.Stamp;
begin
for J in 1 .. I loop
String_Builder.Append (B, "some item");
end loop;
Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B2, 512);
for J in 1 .. I loop
String_Builder.Append (B2, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
String_Builder.Set_Block_Size (B3, 1024);
for J in 1 .. I loop
String_Builder.Append (B3, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
for J in 1 .. I loop
Ada.Strings.Unbounded.Append (U, "some item");
end loop;
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
declare
R : constant String := String_Builder.To_Array (B);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
declare
R : constant String := Ada.Strings.Unbounded.To_String (U);
pragma Unreferenced (R);
begin
Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds);
end;
end;
Ada.Text_IO.New_Line (Perf);
end loop;
end Test_Perf;
end Util.Texts.Builders_Tests;
|
Implement Test_Inline_Append and register the new test for execution
|
Implement Test_Inline_Append and register the new test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9fa9beae9284951ad0f09f8cdc9783f01017b32b
|
awa/src/awa-events-dispatchers-actions.adb
|
awa/src/awa-events-dispatchers-actions.adb
|
-----------------------------------------------------------------------
-- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions
-- Copyright (C) 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Log.Loggers;
with EL.Contexts;
with EL.Contexts.TLS;
with EL.Variables;
with EL.Variables.Default;
with ASF.Beans;
with ASF.Requests;
with ASF.Sessions;
with AWA.Events.Action_Method;
package body AWA.Events.Dispatchers.Actions is
use Ada.Strings.Unbounded;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions");
-- ------------------------------
-- Dispatch the event identified by <b>Event</b>.
-- The event actions which are associated with the event are executed synchronously.
-- ------------------------------
overriding
procedure Dispatch (Manager : in Action_Dispatcher;
Event : in Module_Event'Class) is
use Util.Beans.Objects;
-- Dispatch the event to the event action identified by <b>Action</b>.
procedure Dispatch_One (Action : in Event_Action);
type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record;
overriding
function Get_Value (From : in Event_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Event_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
begin
return Event.Get_Value (Name);
end Get_Value;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
-- ------------------------------
-- Default Resolver
-- ------------------------------
type Event_ELResolver is limited new EL.Contexts.ELResolver with record
Request : ASF.Requests.Request_Access;
Application : AWA.Applications.Application_Access;
end 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;
overriding
procedure Set_Value (Resolver : in out Event_ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in 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
use Util.Beans.Basic;
use type ASF.Requests.Request_Access;
Result : Object;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Scope : ASF.Beans.Scope_Type;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
end if;
if Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
end;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := To_Object (Bean);
if Resolver.Request /= null then
Resolver.Request.Set_Attribute (Key, Result);
else
Variables.Bind (Key, Result);
end if;
return Result;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out Event_ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
elsif Resolver.Request /= null then
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
else
Variables.Bind (To_String (Name), Value);
end if;
end Set_Value;
Local_Event : aliased Event_Bean;
Resolver : aliased Event_ELResolver;
ELContext : aliased EL.Contexts.TLS.TLS_Context;
-- ------------------------------
-- Dispatch the event to the event action identified by <b>Action</b>.
-- ------------------------------
procedure Dispatch_One (Action : in Event_Action) is
use Ada.Exceptions;
Method : EL.Expressions.Method_Info;
begin
Method := Action.Action.Get_Method_Info (Context => ELContext);
if Method.Object.all in Util.Beans.Basic.Bean'Class then
-- If we have a prepare method and the bean provides a Set_Value method,
-- call the preparation method to fill the bean with some values.
EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Method.Object.all),
Action.Properties,
ELContext);
end if;
-- Execute the specified method on the bean and give it the event object.
AWA.Events.Action_Method.Execute (Method => Method,
Param => Event);
-- If an exception is raised by the action, do not propagate it:
-- o We have to dispatch the event to other actions.
-- o The event may be dispatched asynchronously and there is no handler
-- that could handle such exception
exception
when E : others =>
Log.Error ("Error when executing event action {0}: {1}: {2}",
Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E));
end Dispatch_One;
Pos : Event_Action_Lists.Cursor := Manager.Actions.First;
begin
Resolver.Application := Manager.Application;
ELContext.Set_Resolver (Resolver'Unchecked_Access);
ELContext.Set_Variable_Mapper (Variables'Unchecked_Access);
Variables.Bind (Name => "event",
Value => To_Object (Local_Event'Unchecked_Access, STATIC));
while Event_Action_Lists.Has_Element (Pos) loop
Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access);
Event_Action_Lists.Next (Pos);
end loop;
end Dispatch;
-- ------------------------------
-- Add an action invoked when an event is dispatched through this dispatcher.
-- When the event queue dispatches the event, the Ada bean identified by the method action
-- represented by <b>Action</b> is created and initialized by evaluating and setting the
-- parameters defined in <b>Params</b>. The action method is then invoked.
-- ------------------------------
overriding
procedure Add_Action (Manager : in out Action_Dispatcher;
Action : in EL.Expressions.Method_Expression;
Params : in EL.Beans.Param_Vectors.Vector) is
Item : Event_Action;
begin
Item.Action := Action;
Item.Properties := Params;
Manager.Actions.Append (Item);
end Add_Action;
-- ------------------------------
-- Create a new dispatcher associated with the application.
-- ------------------------------
function Create_Dispatcher (Application : in AWA.Applications.Application_Access)
return Dispatcher_Access is
Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with
Application => Application,
others => <>);
begin
return Result.all'Access;
end Create_Dispatcher;
end AWA.Events.Dispatchers.Actions;
|
-----------------------------------------------------------------------
-- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions
-- Copyright (C) 2012, 2015, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Log.Loggers;
with EL.Contexts;
with EL.Contexts.TLS;
with EL.Variables;
with EL.Variables.Default;
with ASF.Beans;
with ASF.Requests;
with ASF.Sessions;
with AWA.Events.Action_Method;
package body AWA.Events.Dispatchers.Actions is
use Ada.Strings.Unbounded;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions");
-- ------------------------------
-- Dispatch the event identified by <b>Event</b>.
-- The event actions which are associated with the event are executed synchronously.
-- ------------------------------
overriding
procedure Dispatch (Manager : in Action_Dispatcher;
Event : in Module_Event'Class) is
use Util.Beans.Objects;
-- Dispatch the event to the event action identified by <b>Action</b>.
procedure Dispatch_One (Action : in Event_Action);
type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record;
overriding
function Get_Value (From : in Event_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Event_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
begin
return Event.Get_Value (Name);
end Get_Value;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
-- ------------------------------
-- Default Resolver
-- ------------------------------
type Event_ELResolver is limited new EL.Contexts.ELResolver with record
Request : ASF.Requests.Request_Access;
Application : AWA.Applications.Application_Access;
end 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;
overriding
procedure Set_Value (Resolver : in out Event_ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in 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
use Util.Beans.Basic;
use type ASF.Requests.Request_Access;
Result : Object;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Scope : ASF.Beans.Scope_Type;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
end if;
if Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
end;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := To_Object (Bean);
if Resolver.Request /= null then
Resolver.Request.Set_Attribute (Key, Result);
else
Variables.Bind (Key, Result);
end if;
return Result;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out Event_ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
elsif Resolver.Request /= null then
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
else
Variables.Bind (To_String (Name), Value);
end if;
end Set_Value;
Local_Event : aliased Event_Bean;
Resolver : aliased Event_ELResolver;
ELContext : aliased EL.Contexts.TLS.TLS_Context;
-- ------------------------------
-- Dispatch the event to the event action identified by <b>Action</b>.
-- ------------------------------
procedure Dispatch_One (Action : in Event_Action) is
use Ada.Exceptions;
Method : EL.Expressions.Method_Info;
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
begin
Method := Action.Action.Get_Method_Info (Context => ELContext);
Bean := Util.Beans.Objects.To_Bean (Method.Object);
if Bean /= null and then Bean.all in Util.Beans.Basic.Bean'Class then
-- If we have a prepare method and the bean provides a Set_Value method,
-- call the preparation method to fill the bean with some values.
EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Bean.all),
Action.Properties,
ELContext);
end if;
-- Execute the specified method on the bean and give it the event object.
AWA.Events.Action_Method.Execute (Method => Method,
Param => Event);
-- If an exception is raised by the action, do not propagate it:
-- o We have to dispatch the event to other actions.
-- o The event may be dispatched asynchronously and there is no handler
-- that could handle such exception
exception
when E : others =>
Log.Error ("Error when executing event action {0}: {1}: {2}",
Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E));
end Dispatch_One;
Pos : Event_Action_Lists.Cursor := Manager.Actions.First;
begin
Resolver.Application := Manager.Application;
ELContext.Set_Resolver (Resolver'Unchecked_Access);
ELContext.Set_Variable_Mapper (Variables'Unchecked_Access);
Variables.Bind (Name => "event",
Value => To_Object (Local_Event'Unchecked_Access, STATIC));
while Event_Action_Lists.Has_Element (Pos) loop
Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access);
Event_Action_Lists.Next (Pos);
end loop;
end Dispatch;
-- ------------------------------
-- Add an action invoked when an event is dispatched through this dispatcher.
-- When the event queue dispatches the event, the Ada bean identified by the method action
-- represented by <b>Action</b> is created and initialized by evaluating and setting the
-- parameters defined in <b>Params</b>. The action method is then invoked.
-- ------------------------------
overriding
procedure Add_Action (Manager : in out Action_Dispatcher;
Action : in EL.Expressions.Method_Expression;
Params : in EL.Beans.Param_Vectors.Vector) is
Item : Event_Action;
begin
Item.Action := Action;
Item.Properties := Params;
Manager.Actions.Append (Item);
end Add_Action;
-- ------------------------------
-- Create a new dispatcher associated with the application.
-- ------------------------------
function Create_Dispatcher (Application : in AWA.Applications.Application_Access)
return Dispatcher_Access is
Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with
Application => Application,
others => <>);
begin
return Result.all'Access;
end Create_Dispatcher;
end AWA.Events.Dispatchers.Actions;
|
Fix compilation with GNAT 2020
|
Fix compilation with GNAT 2020
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f78ec4736fd75998f4f6028ec47814b73672a732
|
src/orka/interface/orka-transforms-simd_matrices.ads
|
src/orka/interface/orka-transforms-simd_matrices.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD;
with Orka.Transforms.SIMD_Vectors;
generic
with package Vectors is new Orka.Transforms.SIMD_Vectors (<>);
type Matrix_Type is array (SIMD.Index_Homogeneous) of Vectors.Vector_Type;
with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type;
with function Multiply_Vector
(Left : Matrix_Type;
Right : Vectors.Vector_Type) return Vectors.Vector_Type;
with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type;
package Orka.Transforms.SIMD_Matrices is
pragma Preelaborate;
subtype Element_Type is Vectors.Element_Type;
subtype Vector_Type is Vectors.Vector_Type;
subtype Matrix4 is Matrix_Type;
subtype Vector4 is Vector_Type;
function Identity_Value return Matrix_Type is
(((1.0, 0.0, 0.0, 0.0),
(0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
with Inline;
function Zero_Point return Vector_Type renames Vectors.Zero_Point;
function T (Offset : Vector_Type) return Matrix_Type;
function Rx (Angle : Element_Type) return Matrix_Type;
function Ry (Angle : Element_Type) return Matrix_Type;
function Rz (Angle : Element_Type) return Matrix_Type;
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type;
function R (Quaternion : Vector_Type) return Matrix_Type;
-- Converts a quaternion to a rotation matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
function S (Factors : Vector_Type) return Matrix_Type;
function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices;
function "*" (Left : Matrix_Type; Right : Vector_Type) return Vector_Type renames Multiply_Vector;
function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a translation transformation to the matrix
function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a scale transformation to the matrix
function Transpose (Matrix : Matrix_Type) return Matrix_Type renames Transpose_Matrix;
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the origin to the matrix
procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type;
Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the given point to the matrix
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Quaternion : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the origin to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate (Matrix : in out Matrix_Type; Quaternion : Vector_Type;
Point : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the given point to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the given point to the matrix
-- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?);
-- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?);
procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type);
-- Add a translation transformation to the matrix
procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type);
procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type);
procedure Transpose (Matrix : in out Matrix_Type);
-- Transpose the matrix
use type Element_Type;
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near;
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => Z_Near >= 0.0 and Z_Far >= 0.0;
end Orka.Transforms.SIMD_Matrices;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD;
with Orka.Transforms.SIMD_Vectors;
generic
with package Vectors is new Orka.Transforms.SIMD_Vectors (<>);
type Matrix_Type is array (SIMD.Index_Homogeneous) of Vectors.Vector_Type;
with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type;
with function Multiply_Vector
(Left : Matrix_Type;
Right : Vectors.Vector_Type) return Vectors.Vector_Type;
with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type;
package Orka.Transforms.SIMD_Matrices is
pragma Preelaborate;
subtype Element_Type is Vectors.Element_Type;
subtype Vector_Type is Vectors.Vector_Type;
subtype Matrix4 is Matrix_Type;
subtype Vector4 is Vector_Type;
function Identity_Value return Matrix_Type is
(((1.0, 0.0, 0.0, 0.0),
(0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
with Inline;
-- Return the identity matrix
function Zero_Point return Vector_Type renames Vectors.Zero_Point;
-- Return a zero vector that indicates a point. The fourth (W) component
-- is 1.
-- Linear transform: a transform in which vector addition and scalar
-- multiplication is preserved.
-- Affine transform: a transform that includes a linear transform and
-- a translation. Parallelism of lines remain unchanged, but lengths
-- and angles may not. A concatenation of affine transforms is affine.
--
-- Orthogonal matrix: the inverse of the matrix is equal to the transpose.
-- A concatenation of orthogonal matrices is orthogonal.
function T (Offset : Vector_Type) return Matrix_Type;
-- Translate points by the given amount
--
-- Matrix is affine.
--
-- The inverse T^-1 (t) = T (-t).
function Rx (Angle : Element_Type) return Matrix_Type;
-- Rotate around the x-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rx^-1 (o) = Rx (-o) = (Rx (o))^T.
function Ry (Angle : Element_Type) return Matrix_Type;
-- Rotate around the y-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Ry^-1 (o) = Ry (-o) = (Ry (o))^T.
function Rz (Angle : Element_Type) return Matrix_Type;
-- Rotate around the z-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rz^-1 (o) = Rz (-o) = (Rz (o))^T.
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type;
-- Rotate around the given axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse is R^-1 (a, o) = R (a, -o) = (R (a, o))^T.
function R (Quaternion : Vector_Type) return Matrix_Type;
-- Converts a quaternion to a rotation matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
function S (Factors : Vector_Type) return Matrix_Type;
-- Scale points by the given amount in the x-, y-, and z-axis
--
-- If all axes are scaled by the same amount, then the matrix is
-- affine.
--
-- The inverse is S^-1 (s) = S (1/s_x, 1/s_y, 1/s_z).
function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices;
function "*" (Left : Matrix_Type; Right : Vector_Type) return Vector_Type renames Multiply_Vector;
function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a translation transformation to the matrix
function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a scale transformation to the matrix
function Transpose (Matrix : Matrix_Type) return Matrix_Type renames Transpose_Matrix;
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the origin to the matrix
procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type;
Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the given point to the matrix
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Quaternion : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the origin to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate (Matrix : in out Matrix_Type; Quaternion : Vector_Type;
Point : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the given point to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the given point to the matrix
-- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?);
-- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?);
procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type);
-- Add a translation transformation to the matrix
procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type);
procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type);
procedure Transpose (Matrix : in out Matrix_Type);
-- Transpose the matrix
use type Element_Type;
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near;
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => Z_Near >= 0.0 and Z_Far >= 0.0;
end Orka.Transforms.SIMD_Matrices;
|
Add some comments to basic transform functions in SIMD_Matrices
|
orka: Add some comments to basic transform functions in SIMD_Matrices
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
67f5cf9d4cbbd08eff3503e0f094e24a78aa60c1
|
regtests/security-permissions-tests.ads
|
regtests/security-permissions-tests.ads
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Security.Permissions.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Add_Permission and Get_Permission_Index
procedure Test_Add_Permission (T : in out Test);
end Security.Permissions.Tests;
|
-----------------------------------------------------------------------
-- Security-permissions-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;
package Security.Permissions.Tests is
package P_Admin is new Permissions.Definition ("admin");
package P_Create is new Permissions.Definition ("create");
package P_Update is new Permissions.Definition ("update");
package P_Delete is new Permissions.Definition ("delete");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Add_Permission and Get_Permission_Index
procedure Test_Add_Permission (T : in out Test);
-- Test the permission created by the Definition package.
procedure Test_Define_Permission (T : in out Test);
-- Test Get_Permission on invalid permission name.
procedure Test_Get_Invalid_Permission (T : in out Test);
end Security.Permissions.Tests;
|
Add new unit tests to check the Permissions.Definition package
|
Add new unit tests to check the Permissions.Definition package
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f750b5c999b35ba4c257fd0e2d7525d8b33b746b
|
mat/src/mat-consoles.adb
|
mat/src/mat-consoles.adb
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with MAT.Formats;
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.Formats.Addr (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the address range and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) is
From_Value : constant String := MAT.Formats.Addr (From);
To_Value : constant String := MAT.Formats.Addr (To);
begin
Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_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.Formats.Size (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 time tick as a duration and print it for the given field.
-- ------------------------------
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref) is
Value : constant String := MAT.Formats.Duration (Duration);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Duration;
-- ------------------------------
-- 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) is
Val : constant String := Util.Strings.Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val, Justify);
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;
Justify : in Justify_Type := J_LEFT) is
Item : String := Ada.Strings.Unbounded.To_String (Value);
Size : constant Natural := Console.Sizes (Field);
begin
if Size <= Item'Length then
Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "...";
Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last));
else
Console_Type'Class (Console).Print_Field (Field, Item, Justify);
end if;
end Print_Field;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with MAT.Formats;
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.Formats.Addr (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the address range and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) is
From_Value : constant String := MAT.Formats.Addr (From);
To_Value : constant String := MAT.Formats.Addr (To);
begin
Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_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.Formats.Size (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 time tick as a duration and print it for the given field.
-- ------------------------------
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref) is
Value : constant String := MAT.Formats.Duration (Duration);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Duration;
-- ------------------------------
-- 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) is
Val : constant String := Util.Strings.Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val, Justify);
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;
Justify : in Justify_Type := J_LEFT) is
Item : String := Ada.Strings.Unbounded.To_String (Value);
Size : constant Natural := Console.Sizes (Field);
begin
if Size <= Item'Length then
Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "...";
Console_Type'Class (Console).Print_Field (Field,
Item (Item'Last - Size + 2 .. Item'Last));
else
Console_Type'Class (Console).Print_Field (Field, Item, Justify);
end if;
end Print_Field;
end MAT.Consoles;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
6362f56a58648eb348f6f038470797e5b6de3092
|
regtests/ado_harness.adb
|
regtests/ado_harness.adb
|
-----------------------------------------------------------------------
-- ADO Databases -- Database 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.
-----------------------------------------------------------------------
with ADO.Testsuite;
with ADO.Drivers;
with Regtests;
with Util.Tests;
with Util.Properties;
procedure ADO_Harness is
procedure Initialize (Props : in Util.Properties.Manager);
procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite,
Initialize);
-- ------------------------------
-- Initialization procedure: setup the database
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager) is
DB : constant String := Props.Get ("test.database",
"sqlite:///regtests.db");
begin
ADO.Drivers.Initialize;
Regtests.Initialize (DB);
end Initialize;
begin
Harness ("ado-tests.xml");
end ADO_Harness;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 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.Testsuite;
with ADO.Drivers.Initializer;
with Regtests;
with Util.Tests;
with Util.Properties;
procedure ADO_Harness is
procedure Initialize (Props : in Util.Properties.Manager);
procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite,
Initialize);
procedure Init_Drivers is new ADO.Drivers.Initializer (Util.Properties.Manager'Class,
ADO.Drivers.Initialize);
-- ------------------------------
-- Initialization procedure: setup the database
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager) is
DB : constant String := Props.Get ("test.database",
"sqlite:///regtests.db");
begin
Init_Drivers (Props);
Regtests.Initialize (DB);
end Initialize;
begin
Harness ("ado-tests.xml");
end ADO_Harness;
|
Initialize the database drivers
|
Initialize the database drivers
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
ee19adca8db9e3c2097feba788cb673ea0cc090a
|
matp/src/events/mat-events-targets.adb
|
matp/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
begin
Target.Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
procedure Update_Size (Event : in out Probe_Event_Type);
procedure Update_Next (Event : in out Probe_Event_Type);
procedure Update_Size (Event : in out Probe_Event_Type) is
begin
Event.Size := Size;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Probe_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Probe_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
begin
Target.Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
procedure Update_Size (Event : in out Probe_Event_Type);
procedure Update_Next (Event : in out Probe_Event_Type);
procedure Update_Size (Event : in out Probe_Event_Type) is
begin
Event.Size := Size;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Probe_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Probe_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Event.Id := Last_Id;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
end MAT.Events.Targets;
|
Update the Event.Id when we insert the event in the list
|
Update the Event.Id when we insert the event in the list
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8121fadc1bead231fc2d31f6ba7596c5c4245670
|
src/babel-files-maps.adb
|
src/babel-files-maps.adb
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Files.Children (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Children, Name);
end Find;
end Babel.Files.Maps;
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Known_Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Knonwn_Dirs, Name);
end Find;
end Babel.Files.Maps;
|
Update the Differential_Container implementation to use the Default_Container
|
Update the Differential_Container implementation to use the Default_Container
|
Ada
|
apache-2.0
|
stcarrez/babel
|
1a5fd42a047e2f91b10e38aed971c7f5b59b33ec
|
matp/src/events/mat-events-targets.adb
|
matp/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
null;
end Finalize;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Finalize procedure for Target_Events
|
Implement the Finalize procedure for Target_Events
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
813815905953288a3ab596134ba399b6ec3a9d89
|
matp/src/symbols/mat-symbols-targets.adb
|
matp/src/symbols/mat-symbols-targets.adb
|
-----------------------------------------------------------------------
-- 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 Bfd.Sections;
with ELF;
with Util.Log.Loggers;
package body MAT.Symbols.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbols associated with a shared library described by the memory region.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path));
end if;
end Load_Symbols;
-- ------------------------------
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use type Bfd.Vma_Type;
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- 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;
Symbol : out Symbol_Info) is
use Ada.Strings.Unbounded;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
Text_Section : Bfd.Sections.Section;
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value.all,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Demangle (Symbols, Symbol);
return;
end if;
end;
end if;
if Bfd.Files.Is_Open (Symbols.File) then
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Bfd.Vma_Type (Addr),
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
Demangle (Symbols, Symbol);
else
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
end if;
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Find_Nearest_Line;
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 Bfd.Sections;
with ELF;
with Util.Log.Loggers;
package body MAT.Symbols.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbols associated with a shared library described by the memory region.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path));
end if;
end Load_Symbols;
-- ------------------------------
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use type Bfd.Vma_Type;
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- 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;
Symbol : out Symbol_Info) is
use Ada.Strings.Unbounded;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
Text_Section : Bfd.Sections.Section;
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value.all,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Demangle (Symbols, Symbol);
return;
end if;
end;
end if;
if Bfd.Files.Is_Open (Symbols.File) then
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Bfd.Vma_Type (Addr),
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
Demangle (Symbols, Symbol);
else
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
end if;
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Find_Nearest_Line;
-- ------------------------------
-- Find the symbol in the symbol table and return the start and end address.
-- ------------------------------
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr) is
use type Bfd.Symbols.Symbol;
Iter : Symbols_Cursor := Symbols.Libraries.First;
begin
while Symbols_Maps.Has_Element (Iter) loop
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter);
Sym : Bfd.Symbols.Symbol;
begin
if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name);
if Sym /= Bfd.Symbols.Null_Symbol then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end;
Symbols_Maps.Next (Iter);
end loop;
end Find_Symbol_Range;
end MAT.Symbols.Targets;
|
Implement the Find_Symbol_Range procedure to lookup in every symbol table for a symbol
|
Implement the Find_Symbol_Range procedure to lookup in every symbol table for a symbol
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3e816209e9c2ed4eda8c1513bbbf0268c8670948
|
regtests/asf-contexts-writer-tests.adb
|
regtests/asf-contexts-writer-tests.adb
|
-----------------------------------------------------------------------
-- Writer Tests - Unit tests for ASF.Contexts.Writer
-- Copyright (C) 2009, 2010, 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.Calendar;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
package body ASF.Contexts.Writer.Tests is
use Util.Tests;
procedure Free_Writer is
new Ada.Unchecked_Deallocation (Object => Test_Writer'Class,
Name => Test_Writer_Access);
procedure Initialize (Stream : in out Test_Writer;
Content_Type : in String;
Encoding : in String;
Size : in Natural) is
Output : ASF.Streams.Print_Stream;
begin
Stream.Content.Initialize (Size => Size);
Output.Initialize (Stream.Content'Unchecked_Access);
Stream.Initialize (Content_Type, Encoding, Output);
end Initialize;
overriding
procedure Write (Stream : in out Test_Writer;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
for I in Buffer'Range loop
Append (Stream.Response, Character'Val (Buffer (I)));
end loop;
end Write;
overriding
procedure Flush (Stream : in out Test_Writer) is
begin
Response_Writer (Stream).Flush;
Stream.Content.Flush (Into => Stream.Response);
end Flush;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
T.Writer := new Test_Writer;
-- use a small buffer to test the flush
T.Writer.Initialize ("text/xml", "UTF-8", 1024);
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
Free_Writer (T.Writer);
end Tear_Down;
-- Test the Start/Write/End_Element methods
procedure Test_Write_Element (T : in out Test) is
begin
T.Writer.Start_Element ("p");
T.Writer.Start_Element ("b");
T.Writer.Write_Element ("i", "italic within a bold");
T.Writer.End_Element ("b");
T.Writer.End_Element ("p");
T.Writer.Flush;
Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>",
T.Writer.Response);
T.Writer.Response := To_Unbounded_String ("");
T.Writer.Start_Element ("div");
T.Writer.Write_Attribute ("title", "A ""S&'%^&<>");
T.Writer.Write_Attribute ("id", "23");
T.Writer.End_Element ("div");
T.Writer.Flush;
Assert_Equals (T, "<div title=""A "S&'%^&<>"" id=""23""></div>",
T.Writer.Response);
end Test_Write_Element;
-- Test the Write_Char/Text methods
procedure Test_Write_Text (T : in out Test) is
use Ada.Calendar;
Start : Ada.Calendar.Time;
D : Duration;
begin
Start := Ada.Calendar.Clock;
T.Writer.Start_Element ("p");
T.Writer.Write_Char ('<');
T.Writer.Write_Char ('>');
T.Writer.Write_Char ('~');
T.Writer.Start_Element ("i");
T.Writer.Write_Text ("""A' <>&");
T.Writer.End_Element ("i");
T.Writer.End_Element ("p");
T.Writer.Flush;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D));
Assert_Equals (T, "<p><>~<i>""A' <>&</i></p>",
T.Writer.Response);
end Test_Write_Text;
package Caller is new Util.Test_Caller (Test, "Contexts.Writer");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Start_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text",
Test_Write_Text'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char",
Test_Write_Text'Access);
end Add_Tests;
end ASF.Contexts.Writer.Tests;
|
-----------------------------------------------------------------------
-- Writer Tests - Unit tests for ASF.Contexts.Writer
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
package body ASF.Contexts.Writer.Tests is
use Util.Tests;
procedure Free_Writer is
new Ada.Unchecked_Deallocation (Object => Test_Writer'Class,
Name => Test_Writer_Access);
procedure Initialize (Stream : in out Test_Writer;
Content_Type : in String;
Encoding : in String;
Size : in Natural) is
Output : ASF.Streams.Print_Stream;
begin
Stream.Content.Initialize (Size => Size);
Output.Initialize (Stream.Content'Unchecked_Access);
Stream.Initialize (Content_Type, Encoding, Output);
end Initialize;
overriding
procedure Write (Stream : in out Test_Writer;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
for I in Buffer'Range loop
Append (Stream.Response, Character'Val (Buffer (I)));
end loop;
end Write;
overriding
procedure Flush (Stream : in out Test_Writer) is
begin
Response_Writer (Stream).Flush;
Stream.Content.Flush (Into => Stream.Response);
end Flush;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
T.Writer := new Test_Writer;
-- use a small buffer to test the flush
T.Writer.Initialize ("text/xml", "UTF-8", 1024);
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
Free_Writer (T.Writer);
end Tear_Down;
-- Test the Start/Write/End_Element methods
procedure Test_Write_Element (T : in out Test) is
begin
T.Writer.Start_Element ("p");
T.Writer.Start_Element ("b");
T.Writer.Write_Element ("i", "italic within a bold");
T.Writer.End_Element ("b");
T.Writer.End_Element ("p");
-- T.Writer.Flush;
Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>",
T.Writer.Response);
T.Writer.Response := To_Unbounded_String ("");
T.Writer.Start_Element ("div");
T.Writer.Write_Attribute ("title", "A ""S&'%^&<>");
T.Writer.Write_Attribute ("id", "23");
T.Writer.End_Element ("div");
-- T.Writer.Flush;
Assert_Equals (T, "<div title=""A "S&'%^&<>"" id=""23""></div>",
T.Writer.Response);
end Test_Write_Element;
-- Test the Write_Char/Text methods
procedure Test_Write_Text (T : in out Test) is
use Ada.Calendar;
Start : Ada.Calendar.Time;
D : Duration;
begin
Start := Ada.Calendar.Clock;
T.Writer.Start_Element ("p");
T.Writer.Write_Char ('<');
T.Writer.Write_Char ('>');
T.Writer.Write_Char ('~');
T.Writer.Start_Element ("i");
T.Writer.Write_Text ("""A' <>&");
T.Writer.End_Element ("i");
T.Writer.End_Element ("p");
-- T.Writer.Flush;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D));
Assert_Equals (T, "<p><>~<i>""A' <>&</i></p>",
T.Writer.Response);
end Test_Write_Text;
package Caller is new Util.Test_Caller (Test, "Contexts.Writer");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Start_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text",
Test_Write_Text'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char",
Test_Write_Text'Access);
end Add_Tests;
end ASF.Contexts.Writer.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
43f1ba5cbc089e7c51db2610d0e1bc39fcfecb9a
|
src/babel-strategies.ads
|
src/babel-strategies.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- 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 Util.Listeners;
with Babel.Files;
with Babel.Files.Queues;
with Babel.Files.Buffers;
with Babel.Streams.Refs;
with Babel.Stores;
with Babel.Filters;
with Babel.Base;
with Babel.Base.Text;
package Babel.Strategies is
type Strategy_Type is abstract tagged limited private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
procedure Peek_Directory (Strategy : in out Strategy_Type;
Directory : out Babel.Files.Directory_Type) is abstract;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in out Babel.Streams.Refs.Stream_Ref);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in Babel.Streams.Refs.Stream_Ref);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in out Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in Babel.Streams.Refs.Stream_Ref);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
-- Set the listeners to inform about changes.
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List);
-- Set the database for use by the strategy.
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access);
private
type Strategy_Type is abstract tagged limited record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
Listeners : access Util.Listeners.List;
-- Database : Babel.Base.Database_Access;
Database : Babel.Base.Text.Text_Database;
end record;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- 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 Util.Listeners;
with Babel.Files;
with Babel.Files.Queues;
with Babel.Files.Buffers;
with Babel.Streams.Refs;
with Babel.Stores;
with Babel.Filters;
with Babel.Base;
with Babel.Base.Text;
package Babel.Strategies is
type Strategy_Type is abstract tagged limited private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
procedure Peek_Directory (Strategy : in out Strategy_Type;
Directory : out Babel.Files.Directory_Type) is abstract;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in out Babel.Streams.Refs.Stream_Ref);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in Babel.Streams.Refs.Stream_Ref);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in out Strategy_Type;
File : in Babel.Files.File_Type;
Stream : in Babel.Streams.Refs.Stream_Ref);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
-- Set the listeners to inform about changes.
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List);
-- Set the database for use by the strategy.
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access);
private
type Strategy_Type is abstract tagged limited record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
Listeners : access Util.Listeners.List;
Database : Babel.Base.Text.Text_Database;
end record;
end Babel.Strategies;
|
Fix presentation style
|
Fix presentation style
|
Ada
|
apache-2.0
|
stcarrez/babel
|
cc330cb1fffac03af5ef85ac1df14ba3a0565105
|
src/gen-model-tables.ads
|
src/gen-model-tables.ads
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the column is auditable (generate code to track changes).
Is_Auditable : Boolean := False;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
-- Whether the serialization operation have to be generated.
Is_Serializable : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the column is auditable (generate code to track changes).
Is_Auditable : Boolean := False;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
-- The number of <<PK>> columns found.
Key_Count : Natural := 0;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
-- Whether the serialization operation have to be generated.
Is_Serializable : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
Add a Key_Count member to the table to count the number of <<PK>> columns in the table
|
Add a Key_Count member to the table to count the number of <<PK>> columns in the table
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
9abc595e63054a058cc5fdabaf80f591bdad1537
|
matp/src/symbols/mat-symbols-targets.adb
|
matp/src/symbols/mat-symbols-targets.adb
|
-----------------------------------------------------------------------
-- 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 Bfd.Sections;
package body MAT.Symbols.Targets is
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- 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) is
Text_Section : Bfd.Sections.Section;
begin
Line := 0;
if Bfd.Files.Is_Open (Symbols.File) then
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Bfd.Vma_Type (Addr),
Name => Name,
Func => Func,
Line => Line);
else
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end if;
exception
when Bfd.NOT_FOUND =>
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Find_Nearest_Line;
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 Bfd.Sections;
package body MAT.Symbols.Targets is
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
procedure Open (Symbols : in out Library_Symbols;
Path : in String) is
begin
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbols associated with a shared library described by the memory region.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Library_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Library_Symbols_Refs.Create;
Syms.Value.Text_Addr := Region.Start_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path));
end Load_Symbols;
-- ------------------------------
-- 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) is
Text_Section : Bfd.Sections.Section;
begin
Line := 0;
if Bfd.Files.Is_Open (Symbols.File) then
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Bfd.Vma_Type (Addr),
Name => Name,
Func => Func,
Line => Line);
else
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end if;
exception
when Bfd.NOT_FOUND =>
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Find_Nearest_Line;
end MAT.Symbols.Targets;
|
Implement the Load_Symbols procedure to load and insert the shared library symbols in the Target_Symbols object
|
Implement the Load_Symbols procedure to load and insert the shared
library symbols in the Target_Symbols object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1037652c6a99819d549dc9c9b42c7d2e69b2d5fb
|
mat/src/mat-targets-readers.ads
|
mat/src/mat-targets-readers.ads
|
-----------------------------------------------------------------------
-- mat-targets-readers - Definition and Analysis of process start events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Events;
with MAT.Readers;
package MAT.Targets.Readers is
type Process_Servant is new MAT.Readers.Reader_Base with record
Target : Target_Type_Access;
Reader : MAT.Readers.Manager;
Process : Target_Process_Type_Access;
end record;
type Process_Reader_Access is access all Process_Servant'Class;
-- Create a new process after the begin event is received from the event stream.
procedure Create_Process (For_Servant : in out Process_Servant;
Pid : in MAT.Types.Target_Process_Ref);
overriding
procedure Dispatch (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message);
-- Register the reader to extract and analyze process events.
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Process_Reader_Access);
-- Initialize the target object to prepare for reading process events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
private
procedure Probe_Begin (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Defs : in MAT.Events.Attribute_Table;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message);
end MAT.Targets.Readers;
|
-----------------------------------------------------------------------
-- mat-targets-readers - Definition and Analysis of process start events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Events;
with MAT.Readers;
package MAT.Targets.Readers is
type Process_Servant is new MAT.Readers.Reader_Base with record
Target : Target_Type_Access;
Reader : MAT.Readers.Manager;
Process : Target_Process_Type_Access;
end record;
type Process_Reader_Access is access all Process_Servant'Class;
-- Create a new process after the begin event is received from the event stream.
procedure Create_Process (For_Servant : in out Process_Servant;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String);
overriding
procedure Dispatch (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message);
-- Register the reader to extract and analyze process events.
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Process_Reader_Access);
-- Initialize the target object to prepare for reading process events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
private
procedure Probe_Begin (For_Servant : in out Process_Servant;
Id : in MAT.Events.Internal_Reference;
Defs : in MAT.Events.Attribute_Table;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message);
end MAT.Targets.Readers;
|
Add the Path parameter in the Create_Process procedure
|
Add the Path parameter in the Create_Process procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b582a5dc50744b50dea7465ed2e669f3a64a7561
|
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
|
stcarrez/ada-util,stcarrez/ada-util
|
1a58e027d20959920ca3e54cc5b202a7cf7fc9d5
|
src/asf-security-servlets.adb
|
src/asf-security-servlets.adb
|
-----------------------------------------------------------------------
-- security-openid-servlets - Servlets for OpenID 2.0 Authentication
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Sessions;
with Util.Beans.Objects;
with Util.Beans.Objects.Records;
with Util.Log.Loggers;
package body ASF.Security.Servlets is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets");
-- Make a package to store the Association in the session.
package Association_Bean is new Util.Beans.Objects.Records (Openid.Association);
subtype Association_Access is Association_Bean.Element_Type_Access;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Openid_Servlet;
Context : in ASF.Servlets.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- Property name that specifies the OpenID callback URL.
OPENID_VERIFY_URL : constant String := "openid.callback_url";
-- Property name that specifies the realm.
OPENID_REALM : constant String := "openid.realm";
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
procedure Initialize (Server : in Openid_Servlet;
Manager : in out OpenID.Manager) is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL);
Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM);
begin
Manager.Initialize (Return_To => Callback_URI,
Name => Realm);
end Initialize;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
URI : constant String := Request.Get_Path_Info;
begin
if URI'Length = 0 then
return "";
end if;
Log.Info ("OpenID authentication with {0}", URI);
return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last));
end Get_Provider_URL;
-- ------------------------------
-- Proceed to the OpenID authentication with an OpenID provider.
-- Find the OpenID provider URL and starts the discovery, association phases
-- during which a private key is obtained from the OpenID provider.
-- After OpenID discovery and association, the user will be redirected to
-- the OpenID provider.
-- ------------------------------
procedure Do_Get (Server : in Request_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Provider : constant String := Server.Get_Provider_URL (Request);
begin
Log.Info ("Request OpenId authentication to {0}", Provider);
if Provider'Length = 0 then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Mgr : OpenID.Manager;
OP : OpenID.End_Point;
Bean : constant Util.Beans.Objects.Object := Association_Bean.Create;
Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean);
begin
Server.Initialize (Mgr);
-- Yadis discovery (get the XRDS file).
Mgr.Discover (Provider, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc.all);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Response.Send_Redirect (Location => Auth_URL);
Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE,
Value => Bean);
end;
end;
end Do_Get;
-- ------------------------------
-- Verify the authentication result that was returned by the OpenID provider.
-- If the authentication succeeded and the signature was correct, sets a
-- user principals on the session.
-- ------------------------------
procedure Do_Get (Server : in Verify_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
use type OpenID.Auth_Result;
type Auth_Params is new OpenID.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return Request.Get_Parameter (Name);
end Get_Parameter;
Session : ASF.Sessions.Session := Request.Get_Session (Create => False);
Bean : Util.Beans.Objects.Object;
Mgr : OpenID.Manager;
Assoc : Association_Access;
Auth : OpenID.Authentication;
Params : Auth_Params;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
Log.Info ("Verify openid authentication");
if not Session.Is_Valid then
Log.Warn ("Session has expired during OpenID authentication process");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE);
if Util.Beans.Objects.Is_Null (Bean) then
Log.Warn ("Verify openid request without active session");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Assoc := Association_Bean.To_Element_Access (Bean);
Server.Initialize (Mgr);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc.all, Params, Auth);
if OpenID.Get_Status (Auth) /= OpenID.AUTHENTICATED then
Log.Info ("Authentication has failed");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Log.Info ("Authentication succeeded for {0}", OpenID.Get_Email (Auth));
-- Get a user principal and set it on the session.
declare
User : ASF.Principals.Principal_Access;
URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url");
begin
Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User);
Session.Set_Principal (User);
Log.Info ("Redirect user to success URL: {0}", URL);
Response.Send_Redirect (Location => URL);
end;
end Do_Get;
-- ------------------------------
-- Create a principal object that correspond to the authenticated user identified
-- by the <b>Auth</b> information. The principal will be attached to the session
-- and will be destroyed when the session is closed.
-- ------------------------------
procedure Create_Principal (Server : in Verify_Auth_Servlet;
Auth : in OpenID.Authentication;
Result : out ASF.Principals.Principal_Access) is
pragma Unreferenced (Server);
P : constant OpenID.Principal_Access := OpenID.Create_Principal (Auth);
begin
Result := P.all'Access;
end Create_Principal;
end ASF.Security.Servlets;
|
-----------------------------------------------------------------------
-- security-openid-servlets - Servlets for OpenID 2.0 Authentication
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Sessions;
with Util.Beans.Objects;
with Util.Beans.Objects.Records;
with Util.Log.Loggers;
package body ASF.Security.Servlets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Servlets");
-- Make a package to store the Association in the session.
package Association_Bean is new Util.Beans.Objects.Records (OpenID.Association);
subtype Association_Access is Association_Bean.Element_Type_Access;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Openid_Servlet;
Context : in ASF.Servlets.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- Property name that specifies the OpenID callback URL.
OPENID_VERIFY_URL : constant String := "openid.callback_url";
-- Property name that specifies the realm.
OPENID_REALM : constant String := "openid.realm";
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
procedure Initialize (Server : in Openid_Servlet;
Manager : in out OpenID.Manager) is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL);
Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM);
begin
Manager.Initialize (Return_To => Callback_URI,
Name => Realm);
end Initialize;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
URI : constant String := Request.Get_Path_Info;
begin
if URI'Length = 0 then
return "";
end if;
Log.Info ("OpenID authentication with {0}", URI);
return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last));
end Get_Provider_URL;
-- ------------------------------
-- Proceed to the OpenID authentication with an OpenID provider.
-- Find the OpenID provider URL and starts the discovery, association phases
-- during which a private key is obtained from the OpenID provider.
-- After OpenID discovery and association, the user will be redirected to
-- the OpenID provider.
-- ------------------------------
procedure Do_Get (Server : in Request_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Provider : constant String := Server.Get_Provider_URL (Request);
begin
Log.Info ("Request OpenId authentication to {0}", Provider);
if Provider'Length = 0 then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Mgr : OpenID.Manager;
OP : OpenID.End_Point;
Bean : constant Util.Beans.Objects.Object := Association_Bean.Create;
Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean);
begin
Server.Initialize (Mgr);
-- Yadis discovery (get the XRDS file).
Mgr.Discover (Provider, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc.all);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Response.Send_Redirect (Location => Auth_URL);
Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE,
Value => Bean);
end;
end;
end Do_Get;
-- ------------------------------
-- Verify the authentication result that was returned by the OpenID provider.
-- If the authentication succeeded and the signature was correct, sets a
-- user principals on the session.
-- ------------------------------
procedure Do_Get (Server : in Verify_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
use type OpenID.Auth_Result;
type Auth_Params is new OpenID.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return Request.Get_Parameter (Name);
end Get_Parameter;
Session : ASF.Sessions.Session := Request.Get_Session (Create => False);
Bean : Util.Beans.Objects.Object;
Mgr : OpenID.Manager;
Assoc : Association_Access;
Auth : OpenID.Authentication;
Params : Auth_Params;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
Log.Info ("Verify openid authentication");
if not Session.Is_Valid then
Log.Warn ("Session has expired during OpenID authentication process");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE);
if Util.Beans.Objects.Is_Null (Bean) then
Log.Warn ("Verify openid request without active session");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Assoc := Association_Bean.To_Element_Access (Bean);
Server.Initialize (Mgr);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc.all, Params, Auth);
if OpenID.Get_Status (Auth) /= OpenID.AUTHENTICATED then
Log.Info ("Authentication has failed");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Log.Info ("Authentication succeeded for {0}", OpenID.Get_Email (Auth));
-- Get a user principal and set it on the session.
declare
User : ASF.Principals.Principal_Access;
URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url");
begin
Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User);
Session.Set_Principal (User);
Log.Info ("Redirect user to success URL: {0}", URL);
Response.Send_Redirect (Location => URL);
end;
end Do_Get;
-- ------------------------------
-- Create a principal object that correspond to the authenticated user identified
-- by the <b>Auth</b> information. The principal will be attached to the session
-- and will be destroyed when the session is closed.
-- ------------------------------
procedure Create_Principal (Server : in Verify_Auth_Servlet;
Auth : in OpenID.Authentication;
Result : out ASF.Principals.Principal_Access) is
pragma Unreferenced (Server);
P : constant OpenID.Principal_Access := OpenID.Create_Principal (Auth);
begin
Result := P.all'Access;
end Create_Principal;
end ASF.Security.Servlets;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
a1576bac2e9a204855602a09eca9ae5bb0b73ccf
|
regtests/util-strings-tests.adb
|
regtests/util-strings-tests.adb
|
-----------------------------------------------------------------------
-- strings.tests -- Unit tests for strings
-- 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;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded.Hash;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Strings.Maps;
with Util.Perfect_Hash;
with Ada.Streams;
with Util.Measures;
package body Util.Strings.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
use Util.Strings.Transforms;
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Javascript",
Test_Escape_Javascript'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Xml",
Test_Escape_Xml'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Capitalize",
Test_Capitalize'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Upper_Case",
Test_To_Upper_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Lower_Case",
Test_To_Lower_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Hex",
Test_To_Hex'Access);
Caller.Add_Test (Suite, "Test Measure",
Test_Measure_Copy'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Index",
Test_Index'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Rindex",
Test_Rindex'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Benchmark",
Test_Measure_Hash'Access);
Caller.Add_Test (Suite, "Test Util.Strings.String_Ref",
Test_String_Ref'Access);
Caller.Add_Test (Suite, "Test perfect hash",
Test_Perfect_Hash'Access);
end Add_Tests;
procedure Test_Escape_Javascript (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Javascript (Content => ASCII.LF & " ""a string"" a 'single quote'",
Into => Result);
Assert_Equals (T, "\n \""a string\"" a \'single quote\'", Result);
Result := To_Unbounded_String ("");
Escape_Javascript (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, "\u001B[m \u00FF", Result);
end Test_Escape_Javascript;
procedure Test_Escape_Xml (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Xml (Content => ASCII.LF & " < ""a string"" a 'single quote' >& ",
Into => Result);
Assert_Equals (T, ASCII.LF & " < ""a string"" a 'single quote' >& ",
Result);
Result := To_Unbounded_String ("");
Escape_Xml (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, ASCII.ESC & "[m ÿ", Result);
end Test_Escape_Xml;
procedure Test_Capitalize (T : in out Test) is
Result : Unbounded_String;
begin
Assert_Equals (T, "Capitalize_A_String", Capitalize ("capITalIZe_a_strING"));
Capitalize ("CapAS_String", Result);
Assert_Equals (T, "Capas_String", Result);
end Test_Capitalize;
procedure Test_To_Upper_Case (T : in out Test) is
begin
Assert_Equals (T, "UPPERCASE_0123_STR", To_Upper_Case ("upperCase_0123_str"));
end Test_To_Upper_Case;
procedure Test_To_Lower_Case (T : in out Test) is
begin
Assert_Equals (T, "lowercase_0123_str", To_Lower_Case ("LowERCase_0123_STR"));
end Test_To_Lower_Case;
procedure Test_To_Hex (T : in out Test) is
Result : Unbounded_String;
begin
To_Hex (Result, Character'Val (23));
Assert_Equals (T, "\u0017", Result);
To_Hex (Result, Character'Val (31));
Assert_Equals (T, "\u0017\u001F", Result);
To_Hex (Result, Character'Val (255));
Assert_Equals (T, "\u0017\u001F\u00FF", Result);
end Test_To_Hex;
procedure Test_Measure_Copy (T : in out Test) is
pragma Unreferenced (T);
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 10_024) := (others => 23);
pragma Suppress (All_Checks, Buf);
begin
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
begin
for I in Buf'Range loop
Append (R, Character'Val (Buf (I)));
end loop;
Util.Measures.Report (T, "Stream transform using Append (1024 bytes)");
end;
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
S : String (1 .. 10_024);
pragma Suppress (All_Checks, S);
begin
for I in Buf'Range loop
S (Natural (I)) := Character'Val (Buf (I));
end loop;
Append (R, S);
Util.Measures.Report (T, "Stream transform using temporary string (1024 bytes)");
end;
-- declare
-- T : Util.Measures.Stamp;
-- R : Ada.Strings.Unbounded.Unbounded_String;
-- P : constant Ptr := new String (1 .. Buf'Length);
--
-- pragma Suppress (All_Checks, P);
-- begin
-- for I in P'Range loop
-- P (I) := Character'Val (Buf (Ada.Streams.Stream_Element_Offset (I)));
-- end loop;
-- Ada.Strings.Unbounded.Aux.Set_String (R, P.all'Access);
-- Util.Measures.Report (T, "Stream transform using Aux string (1024 bytes)");
-- end;
end Test_Measure_Copy;
-- Test the Index operation
procedure Test_Index (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Index (Str, 'q');
end loop;
Util.Measures.Report (St, "Util.Strings.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "q");
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
end Test_Index;
-- Test the Rindex operation
procedure Test_Rindex (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Rindex (Str, '0');
end loop;
Util.Measures.Report (St, "Util.Strings.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "0", Ada.Strings.Backward);
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
end Test_Rindex;
package String_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => Unbounded_String,
Hash => Hash,
Equivalent_Keys => "=");
package String_Ref_Map is new Ada.Containers.Hashed_Maps
(Key_Type => String_Ref,
Element_Type => String_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
-- Do some benchmark on String -> X hash mapped.
procedure Test_Measure_Hash (T : in out Test) is
KEY : aliased constant String := "testing";
Str_Map : Util.Strings.Maps.Map;
Ptr_Map : Util.Strings.String_Access_Map.Map;
Ref_Map : String_Ref_Map.Map;
Unb_Map : String_Map.Map;
Name : String_Access := new String '(KEY);
Ref : constant String_Ref := To_String_Ref (KEY);
begin
Str_Map.Insert (Name.all, Name.all);
Ptr_Map.Insert (Name.all'Access, Name.all'Access);
Unb_Map.Insert (To_Unbounded_String (KEY), To_Unbounded_String (KEY));
Ref_Map.Insert (Ref, Ref);
-- Performance of Hashed_Map Name_Access -> Name_Access
-- (the fastest hash)
declare
St : Util.Measures.Stamp;
Pos : constant Strings.String_Access_Map.Cursor := Ptr_Map.Find (KEY'Unchecked_Access);
Val : constant Name_Access := Util.Strings.String_Access_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Access_Maps.Find+Element");
Assert_Equals (T, "testing", Val.all, "Invalid value returned");
end;
-- Performance of Hashed_Map String_Ref -> String_Ref
-- (almost same performance as Hashed_Map Name_Access -> Name_Access)
declare
St : Util.Measures.Stamp;
Pos : constant String_Ref_Map.Cursor := Ref_Map.Find (Ref);
Val : constant String_Ref := String_Ref_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Ref_Maps.Find+Element");
Assert_Equals (T, "testing", String '(To_String (Val)), "Invalid value returned");
end;
-- Performance of Hashed_Map Unbounded_String -> Unbounded_String
-- (little overhead due to String copy made by Unbounded_String)
declare
St : Util.Measures.Stamp;
Pos : constant String_Map.Cursor := Unb_Map.Find (To_Unbounded_String (KEY));
Val : constant Unbounded_String := String_Map.Element (Pos);
begin
Util.Measures.Report (St, "Hashed_Maps<Unbounded,Unbounded..Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
-- Performance for Indefinite_Hashed_Map String -> String
-- (the slowest hash, string copy to get the result, pointer to key and element
-- in the hash map implementation)
declare
St : Util.Measures.Stamp;
Pos : constant Util.Strings.Maps.Cursor := Str_Map.Find (KEY);
Val : constant String := Util.Strings.Maps.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.Maps.Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
Free (Name);
end Test_Measure_Hash;
-- ------------------------------
-- Test String_Ref creation
-- ------------------------------
procedure Test_String_Ref (T : in out Test) is
R1 : String_Ref := To_String_Ref ("testing a string");
begin
for I in 1 .. 1_000 loop
declare
S : constant String (1 .. I) := (others => 'x');
R2 : constant String_Ref := To_String_Ref (S);
begin
Assert_Equals (T, S, To_String (R2), "Invalid String_Ref");
T.Assert (R2 = S, "Invalid comparison");
Assert_Equals (T, I, Length (R2), "Invalid length");
R1 := R2;
T.Assert (R1 = R2, "Invalid String_Ref copy");
end;
end loop;
end Test_String_Ref;
-- Test perfect hash (samples/gperfhash)
procedure Test_Perfect_Hash (T : in out Test) is
begin
for I in Util.Perfect_Hash.Keywords'Range loop
declare
K : constant String := Util.Perfect_Hash.Keywords (I).all;
begin
Assert_Equals (T, I, Util.Perfect_Hash.Hash (K),
"Invalid hash");
Assert_Equals (T, I, Util.Perfect_Hash.Hash (To_Lower_Case (K)),
"Invalid hash");
Assert (T, Util.Perfect_Hash.Is_Keyword (K), "Keyword " & K & " is not a keyword");
Assert (T, Util.Perfect_Hash.Is_Keyword (To_Lower_Case (K)),
"Keyword " & K & " is not a keyword");
end;
end loop;
end Test_Perfect_Hash;
end Util.Strings.Tests;
|
-----------------------------------------------------------------------
-- strings.tests -- Unit tests for strings
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded.Hash;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Strings.Maps;
with Util.Perfect_Hash;
with Ada.Streams;
with Util.Measures;
package body Util.Strings.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
use Util.Strings.Transforms;
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Javascript",
Test_Escape_Javascript'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Xml",
Test_Escape_Xml'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Capitalize",
Test_Capitalize'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Upper_Case",
Test_To_Upper_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Lower_Case",
Test_To_Lower_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Hex",
Test_To_Hex'Access);
Caller.Add_Test (Suite, "Test Measure",
Test_Measure_Copy'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Index",
Test_Index'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Rindex",
Test_Rindex'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Benchmark",
Test_Measure_Hash'Access);
Caller.Add_Test (Suite, "Test Util.Strings.String_Ref",
Test_String_Ref'Access);
Caller.Add_Test (Suite, "Test perfect hash",
Test_Perfect_Hash'Access);
end Add_Tests;
procedure Test_Escape_Javascript (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Javascript (Content => ASCII.LF & " ""a string"" a 'single quote'",
Into => Result);
Assert_Equals (T, "\n \""a string\"" a \'single quote\'", Result);
Result := To_Unbounded_String ("");
Escape_Javascript (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, "\u001B[m " & Character'Val (255), Result);
end Test_Escape_Javascript;
procedure Test_Escape_Xml (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Xml (Content => ASCII.LF & " < ""a string"" a 'single quote' >& ",
Into => Result);
Assert_Equals (T, ASCII.LF & " < ""a string"" a 'single quote' >& ",
Result);
Result := To_Unbounded_String ("");
Escape_Xml (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, ASCII.ESC & "[m ÿ", Result);
end Test_Escape_Xml;
procedure Test_Capitalize (T : in out Test) is
Result : Unbounded_String;
begin
Assert_Equals (T, "Capitalize_A_String", Capitalize ("capITalIZe_a_strING"));
Capitalize ("CapAS_String", Result);
Assert_Equals (T, "Capas_String", Result);
end Test_Capitalize;
procedure Test_To_Upper_Case (T : in out Test) is
begin
Assert_Equals (T, "UPPERCASE_0123_STR", To_Upper_Case ("upperCase_0123_str"));
end Test_To_Upper_Case;
procedure Test_To_Lower_Case (T : in out Test) is
begin
Assert_Equals (T, "lowercase_0123_str", To_Lower_Case ("LowERCase_0123_STR"));
end Test_To_Lower_Case;
procedure Test_To_Hex (T : in out Test) is
Result : Unbounded_String;
begin
To_Hex (Result, Character'Val (23));
Assert_Equals (T, "\u0017", Result);
To_Hex (Result, Character'Val (31));
Assert_Equals (T, "\u0017\u001F", Result);
To_Hex (Result, Character'Val (255));
Assert_Equals (T, "\u0017\u001F\u00FF", Result);
end Test_To_Hex;
procedure Test_Measure_Copy (T : in out Test) is
pragma Unreferenced (T);
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 10_024) := (others => 23);
pragma Suppress (All_Checks, Buf);
begin
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
begin
for I in Buf'Range loop
Append (R, Character'Val (Buf (I)));
end loop;
Util.Measures.Report (T, "Stream transform using Append (1024 bytes)");
end;
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
S : String (1 .. 10_024);
pragma Suppress (All_Checks, S);
begin
for I in Buf'Range loop
S (Natural (I)) := Character'Val (Buf (I));
end loop;
Append (R, S);
Util.Measures.Report (T, "Stream transform using temporary string (1024 bytes)");
end;
-- declare
-- T : Util.Measures.Stamp;
-- R : Ada.Strings.Unbounded.Unbounded_String;
-- P : constant Ptr := new String (1 .. Buf'Length);
--
-- pragma Suppress (All_Checks, P);
-- begin
-- for I in P'Range loop
-- P (I) := Character'Val (Buf (Ada.Streams.Stream_Element_Offset (I)));
-- end loop;
-- Ada.Strings.Unbounded.Aux.Set_String (R, P.all'Access);
-- Util.Measures.Report (T, "Stream transform using Aux string (1024 bytes)");
-- end;
end Test_Measure_Copy;
-- Test the Index operation
procedure Test_Index (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Index (Str, 'q');
end loop;
Util.Measures.Report (St, "Util.Strings.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "q");
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
end Test_Index;
-- Test the Rindex operation
procedure Test_Rindex (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Rindex (Str, '0');
end loop;
Util.Measures.Report (St, "Util.Strings.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "0", Ada.Strings.Backward);
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
end Test_Rindex;
package String_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => Unbounded_String,
Hash => Hash,
Equivalent_Keys => "=");
package String_Ref_Map is new Ada.Containers.Hashed_Maps
(Key_Type => String_Ref,
Element_Type => String_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
-- Do some benchmark on String -> X hash mapped.
procedure Test_Measure_Hash (T : in out Test) is
KEY : aliased constant String := "testing";
Str_Map : Util.Strings.Maps.Map;
Ptr_Map : Util.Strings.String_Access_Map.Map;
Ref_Map : String_Ref_Map.Map;
Unb_Map : String_Map.Map;
Name : String_Access := new String '(KEY);
Ref : constant String_Ref := To_String_Ref (KEY);
begin
Str_Map.Insert (Name.all, Name.all);
Ptr_Map.Insert (Name.all'Access, Name.all'Access);
Unb_Map.Insert (To_Unbounded_String (KEY), To_Unbounded_String (KEY));
Ref_Map.Insert (Ref, Ref);
-- Performance of Hashed_Map Name_Access -> Name_Access
-- (the fastest hash)
declare
St : Util.Measures.Stamp;
Pos : constant Strings.String_Access_Map.Cursor := Ptr_Map.Find (KEY'Unchecked_Access);
Val : constant Name_Access := Util.Strings.String_Access_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Access_Maps.Find+Element");
Assert_Equals (T, "testing", Val.all, "Invalid value returned");
end;
-- Performance of Hashed_Map String_Ref -> String_Ref
-- (almost same performance as Hashed_Map Name_Access -> Name_Access)
declare
St : Util.Measures.Stamp;
Pos : constant String_Ref_Map.Cursor := Ref_Map.Find (Ref);
Val : constant String_Ref := String_Ref_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Ref_Maps.Find+Element");
Assert_Equals (T, "testing", String '(To_String (Val)), "Invalid value returned");
end;
-- Performance of Hashed_Map Unbounded_String -> Unbounded_String
-- (little overhead due to String copy made by Unbounded_String)
declare
St : Util.Measures.Stamp;
Pos : constant String_Map.Cursor := Unb_Map.Find (To_Unbounded_String (KEY));
Val : constant Unbounded_String := String_Map.Element (Pos);
begin
Util.Measures.Report (St, "Hashed_Maps<Unbounded,Unbounded..Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
-- Performance for Indefinite_Hashed_Map String -> String
-- (the slowest hash, string copy to get the result, pointer to key and element
-- in the hash map implementation)
declare
St : Util.Measures.Stamp;
Pos : constant Util.Strings.Maps.Cursor := Str_Map.Find (KEY);
Val : constant String := Util.Strings.Maps.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.Maps.Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
Free (Name);
end Test_Measure_Hash;
-- ------------------------------
-- Test String_Ref creation
-- ------------------------------
procedure Test_String_Ref (T : in out Test) is
R1 : String_Ref := To_String_Ref ("testing a string");
begin
for I in 1 .. 1_000 loop
declare
S : constant String (1 .. I) := (others => 'x');
R2 : constant String_Ref := To_String_Ref (S);
begin
Assert_Equals (T, S, To_String (R2), "Invalid String_Ref");
T.Assert (R2 = S, "Invalid comparison");
Assert_Equals (T, I, Length (R2), "Invalid length");
R1 := R2;
T.Assert (R1 = R2, "Invalid String_Ref copy");
end;
end loop;
end Test_String_Ref;
-- Test perfect hash (samples/gperfhash)
procedure Test_Perfect_Hash (T : in out Test) is
begin
for I in Util.Perfect_Hash.Keywords'Range loop
declare
K : constant String := Util.Perfect_Hash.Keywords (I).all;
begin
Assert_Equals (T, I, Util.Perfect_Hash.Hash (K),
"Invalid hash");
Assert_Equals (T, I, Util.Perfect_Hash.Hash (To_Lower_Case (K)),
"Invalid hash");
Assert (T, Util.Perfect_Hash.Is_Keyword (K), "Keyword " & K & " is not a keyword");
Assert (T, Util.Perfect_Hash.Is_Keyword (To_Lower_Case (K)),
"Keyword " & K & " is not a keyword");
end;
end loop;
end Test_Perfect_Hash;
end Util.Strings.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
3100389715dc88389482b572b3530cdd1d36084b
|
awa/regtests/awa-blogs-modules-tests.adb
|
awa/regtests/awa-blogs-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
Text => "The new post content",
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6ba8011934a13d54e619a376599a59be0c60bf4c
|
src/asf-responses-mockup.adb
|
src/asf-responses-mockup.adb
|
-----------------------------------------------------------------------
-- asf.responses -- ASF Requests
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Responses</b> package is an Ada implementation of
-- the Java servlet response (JSR 315 5. The Response).
package body ASF.Responses.Mockup is
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name);
begin
return Util.Strings.Maps.Has_Element (Pos);
end Contains_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor);
procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is
begin
Process.all (Name => Util.Strings.Maps.Key (Position),
Value => Util.Strings.Maps.Element (Position));
end Process_Wrapper;
begin
Resp.Headers.Iterate (Process => Process_Wrapper'Access);
end Iterate_Headers;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
Resp.Headers.Include (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if Resp.Headers.Contains (Name) then
Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF
& Name & ": " & Value);
else
Resp.Headers.Insert (Name, Value);
end if;
end Add_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the response. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Resp : in Response;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Get the content written to the mockup output stream.
-- ------------------------------
procedure Read_Content (Resp : in out Response;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Resp.Content.Read (Into => Into);
end Read_Content;
-- ------------------------------
-- Clear the response content.
-- This operation removes any content held in the output stream, clears the status,
-- removes any header in the response.
-- ------------------------------
procedure Clear (Resp : in out Response) is
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Resp.Read_Content (Content);
Resp.Status := SC_OK;
Resp.Headers.Clear;
end Clear;
-- ------------------------------
-- Initialize the response mockup output stream.
-- ------------------------------
overriding
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (128 * 1024);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
end ASF.Responses.Mockup;
|
-----------------------------------------------------------------------
-- asf.responses -- ASF Requests
-- Copyright (C) 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Responses</b> package is an Ada implementation of
-- the Java servlet response (JSR 315 5. The Response).
package body ASF.Responses.Mockup is
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name);
begin
return Util.Strings.Maps.Has_Element (Pos);
end Contains_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor);
procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is
begin
Process.all (Name => Util.Strings.Maps.Key (Position),
Value => Util.Strings.Maps.Element (Position));
end Process_Wrapper;
begin
Resp.Headers.Iterate (Process => Process_Wrapper'Access);
end Iterate_Headers;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
Resp.Headers.Include (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if Resp.Headers.Contains (Name) then
Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF
& Value);
else
Resp.Headers.Insert (Name, Value);
end if;
end Add_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the response. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Resp : in Response;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Get the content written to the mockup output stream.
-- ------------------------------
procedure Read_Content (Resp : in out Response;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Resp.Headers.Include ("Content-Type", Resp.Get_Content_Type);
Resp.Content.Read (Into => Into);
end Read_Content;
-- ------------------------------
-- Clear the response content.
-- This operation removes any content held in the output stream, clears the status,
-- removes any header in the response.
-- ------------------------------
procedure Clear (Resp : in out Response) is
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Resp.Read_Content (Content);
Resp.Status := SC_OK;
Resp.Headers.Clear;
end Clear;
-- ------------------------------
-- Initialize the response mockup output stream.
-- ------------------------------
overriding
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (128 * 1024);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
end ASF.Responses.Mockup;
|
Include the Content-Type header at the end so that tests can get it as a header
|
Include the Content-Type header at the end so that tests can get it as a header
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
1292b72153e375f37112af219c333c0d2629abd3
|
samples/launch.adb
|
samples/launch.adb
|
-----------------------------------------------------------------------
-- launch -- Launch an external process redirecting the input and output
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
procedure Launch is
use Ada.Strings.Unbounded;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream
Pipe.Open ("nslookup", Util.Processes.READ_WRITE);
Buffer.Initialize (null, Pipe'Unchecked_Access, 1024);
Print.Initialize (Pipe'Unchecked_Access);
-- Write on the 'nslookup' input pipe a list of domains to resolve.
Print.Write ("www.google.com" & ASCII.LF);
Print.Write ("set type=NS" & ASCII.LF);
Print.Write ("www.google.com" & ASCII.LF);
Print.Write ("set type=MX" & ASCII.LF);
Print.Write ("www.google.com" & ASCII.LF);
Print.Close;
-- Read the 'nslookup' output.
Buffer.Read (Content);
Pipe.Close;
Ada.Text_IO.Put_Line ("Result lenght: " & Integer'Image (Length (Content)));
Ada.Text_IO.Put_Line ("Exit status: " & Integer'Image (Pipe.Get_Exit_Status));
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
end Launch;
|
-----------------------------------------------------------------------
-- launch -- Launch an external process redirecting the input and output
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
procedure Launch is
use Ada.Strings.Unbounded;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream
Pipe.Open ("nslookup", Util.Processes.READ_WRITE);
Buffer.Initialize (Pipe'Unchecked_Access, 1024);
Print.Initialize (Pipe'Unchecked_Access);
-- Write on the 'nslookup' input pipe a list of domains to resolve.
Print.Write ("www.google.com" & ASCII.LF);
Print.Write ("set type=NS" & ASCII.LF);
Print.Write ("www.google.com" & ASCII.LF);
Print.Write ("set type=MX" & ASCII.LF);
Print.Write ("www.google.com" & ASCII.LF);
Print.Close;
-- Read the 'nslookup' output.
Buffer.Read (Content);
Pipe.Close;
Ada.Text_IO.Put_Line ("Result lenght: " & Integer'Image (Length (Content)));
Ada.Text_IO.Put_Line ("Exit status: " & Integer'Image (Pipe.Get_Exit_Status));
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
end Launch;
|
Use the Input_Buffer_Stream
|
Use the Input_Buffer_Stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8f0a30c31addcd0446392f1dcf97fff2e1b3ff2b
|
regtests/asf-routes-tests.adb
|
regtests/asf-routes-tests.adb
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Measures;
with Util.Log.Loggers;
with Util.Test_Caller;
with EL.Contexts.Default;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I));
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index).Value;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associted with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index).Value;
begin
Router.Add_Route (Path, Route, T.ELContext.all);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
Add_Route (T, Router, "/ajax/*", 7, Bean);
Add_Route (T, Router, "*.html", 8, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/view/index.html", 8, Bean);
Add_Route (T, Router, "/ajax/timeKeeper/*", 9, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/ajax/timeKeeper/save", 9, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.html", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (fixed path)");
end;
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (extension)");
end;
end Test_Iterate;
end ASF.Routes.Tests;
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Measures;
with Util.Log.Loggers;
with Util.Test_Caller;
with EL.Contexts.Default;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I));
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index).Value;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associated with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
begin
Route := T.Routes (Index);
end Insert;
begin
Router.Add_Route (Path, T.ELContext.all, Insert'Access);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
Add_Route (T, Router, "/ajax/*", 7, Bean);
Add_Route (T, Router, "*.html", 8, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/view/index.html", 8, Bean);
Add_Route (T, Router, "/ajax/timeKeeper/*", 9, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/ajax/timeKeeper/save", 9, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.html", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (fixed path)");
end;
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (extension)");
end;
end Test_Iterate;
end ASF.Routes.Tests;
|
Update the route test creation
|
Update the route test creation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2d52387c051b98c2f7a99621625ec0938ee024fd
|
samples/rest/monitor.adb
|
samples/rest/monitor.adb
|
-----------------------------------------------------------------------
-- monitor - A simple monitor API
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Responses;
with ASF.Rest.Definition;
package body Monitor is
type Monitor_Array is array (1 .. MAX_MONITOR) of Monitor_Data;
Monitors : Monitor_Array;
-- Get values of the monitor.
procedure Get_Values (D : in out Mon;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class) is
Id : constant String := Req.Get_Path_Parameter (1);
Pos : Positive;
begin
Pos := Positive'Value (Id);
-- Monitors (Pos).Put (0);
-- Get the monitor values.
declare
Values : constant Value_Array := Monitors (Pos).Get_Values;
begin
-- Write the JSON/XML document.
Stream.Start_Document;
Stream.Start_Array ("values");
for V of Values loop
Stream.Write_Long_Entity ("value", Long_Long_Integer (V));
end loop;
Stream.End_Array ("values");
Stream.End_Document;
end;
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_NOT_FOUND);
end Get_Values;
-- PUT /mon/:id
procedure Put_Value (D : in out Mon;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class) is
Id : constant String := Req.Get_Path_Parameter (1);
Pos : Positive;
Val : Natural;
begin
Pos := Positive'Value (Id);
begin
Val := Natural'Value (Req.Get_Parameter ("value"));
Monitors (Pos).Put (Val);
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_BAD_REQUEST);
end;
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_NOT_FOUND);
end Put_Value;
protected body Monitor_Data is
procedure Put (Value : in Natural) is
use type Ada.Calendar.Time;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Dt : constant Duration := Now - Slot_Start;
Cnt : Natural := Natural (Dt / Slot_Size);
begin
if Cnt > 0 then
while Cnt > 0 loop
Cnt := Cnt - 1;
Pos := Pos + 1;
if Pos > Values'Last then
Pos := Values'First;
Value_Count := Values'Length;
elsif Value_Count < Values'Length then
Value_Count := Value_Count + 1;
end if;
Slot_Start := Slot_Start + Slot_Size;
end loop;
end if;
Values (Pos) := Value;
end Put;
procedure Put (Value : in Natural; Slot : in Natural) is
begin
null;
end Put;
function Get_Values return Value_Array is
Result : Value_Array (1 .. Value_Count);
Cnt : Natural;
N : Natural;
begin
if Value_Count = Values'Length then
Cnt := Values'Last - Pos;
else
Cnt := 0;
end if;
if Cnt > 0 then
Result (1 .. Cnt) := Values (Pos + 1 .. Pos + 1 + Cnt - 1);
N := Cnt + 1;
else
N := 1;
end if;
if Value_Count = Values'Length then
Cnt := Pos;
else
Cnt := Pos - 1;
end if;
if Cnt > 0 then
Result (N .. N + Cnt - 1) := Values (1 .. Cnt);
end if;
return Result;
end Get_Values;
end Monitor_Data;
end Monitor;
|
-----------------------------------------------------------------------
-- monitor - A simple monitor API
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Responses;
with ASF.Rest.Definition;
package body Monitor is
type Monitor_Array is array (1 .. MAX_MONITOR) of Monitor_Data;
Monitors : Monitor_Array;
-- Get values of the monitor.
procedure Get_Values (Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class) is
Id : constant String := Req.Get_Path_Parameter (1);
Pos : Positive;
begin
Pos := Positive'Value (Id);
-- Monitors (Pos).Put (0);
-- Get the monitor values.
declare
Values : constant Value_Array := Monitors (Pos).Get_Values;
begin
-- Write the JSON/XML document.
Stream.Start_Document;
Stream.Start_Array ("values");
for V of Values loop
Stream.Write_Long_Entity ("value", Long_Long_Integer (V));
end loop;
Stream.End_Array ("values");
Stream.End_Document;
end;
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_NOT_FOUND);
end Get_Values;
-- PUT /mon/:id
procedure Put_Value (Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class) is
Id : constant String := Req.Get_Path_Parameter (1);
Pos : Positive;
Val : Natural;
begin
Pos := Positive'Value (Id);
begin
Val := Natural'Value (Req.Get_Parameter ("value"));
Monitors (Pos).Put (Val);
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_BAD_REQUEST);
end;
exception
when others =>
Reply.Set_Status (ASF.Responses.SC_NOT_FOUND);
end Put_Value;
protected body Monitor_Data is
procedure Put (Value : in Natural) is
use type Ada.Calendar.Time;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Dt : constant Duration := Now - Slot_Start;
Cnt : Natural := Natural (Dt / Slot_Size);
begin
if Cnt > 0 then
while Cnt > 0 loop
Cnt := Cnt - 1;
Pos := Pos + 1;
if Pos > Values'Last then
Pos := Values'First;
Value_Count := Values'Length;
elsif Value_Count < Values'Length then
Value_Count := Value_Count + 1;
end if;
Slot_Start := Slot_Start + Slot_Size;
end loop;
end if;
Values (Pos) := Value;
end Put;
procedure Put (Value : in Natural; Slot : in Natural) is
begin
null;
end Put;
function Get_Values return Value_Array is
Result : Value_Array (1 .. Value_Count);
Cnt : Natural;
N : Natural;
begin
if Value_Count = Values'Length then
Cnt := Values'Last - Pos;
else
Cnt := 0;
end if;
if Cnt > 0 then
Result (1 .. Cnt) := Values (Pos + 1 .. Pos + 1 + Cnt - 1);
N := Cnt + 1;
else
N := 1;
end if;
if Value_Count = Values'Length then
Cnt := Pos;
else
Cnt := Pos - 1;
end if;
if Cnt > 0 then
Result (N .. N + Cnt - 1) := Values (1 .. Cnt);
end if;
return Result;
end Get_Values;
end Monitor_Data;
end Monitor;
|
Simplify the REST API operations
|
Simplify the REST API operations
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2360f18ecbd40fd4a10d8c6010565548b935bce7
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)",
Test_Admin_List_Posts'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)",
Test_Admin_List_Comments'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)",
Test_Admin_Blog_Stats'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)",
Test_Update_Publish_Date'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid",
ASF.Responses.SC_NOT_FOUND);
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply,
"Blog post page is invalid"
);
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- ------------------------------
-- Test updating a post by simulating web requests.
-- ------------------------------
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "POST_PUBLISHED");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
-- ------------------------------
-- Test updating the publication date by simulating web requests.
-- ------------------------------
procedure Test_Update_Publish_Date (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post_id", To_String (T.Post_Ident));
Request.Set_Parameter ("blog_id", Ident);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html");
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "POST_PUBLISHED");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
Request.Set_Parameter ("publish-date", "");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Publish_Date;
-- ------------------------------
-- Test listing the blog posts.
-- ------------------------------
procedure Test_Admin_List_Posts (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html");
ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid");
end Test_Admin_List_Posts;
-- ------------------------------
-- Test listing the blog comments.
-- ------------------------------
procedure Test_Admin_List_Comments (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident,
"blog-list-comments.html");
ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply,
"Blog admin comments page is invalid");
end Test_Admin_List_Comments;
-- ------------------------------
-- Test getting the JSON blog stats (for graphs).
-- ------------------------------
procedure Test_Admin_Blog_Stats (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats",
"blog-stats.html");
ASF.Tests.Assert_Contains (T, "data", Reply,
"Blog admin stats page is invalid");
end Test_Admin_Blog_Stats;
end AWA.Blogs.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)",
Test_Admin_List_Posts'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)",
Test_Admin_List_Comments'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)",
Test_Admin_Blog_Stats'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)",
Test_Update_Publish_Date'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid",
ASF.Responses.SC_NOT_FOUND);
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply,
"Blog post page is invalid"
);
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
Request.Set_Parameter ("format", "dotclear");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- ------------------------------
-- Test updating a post by simulating web requests.
-- ------------------------------
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "POST_PUBLISHED");
Request.Set_Parameter ("format", "dotclear");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
-- ------------------------------
-- Test updating the publication date by simulating web requests.
-- ------------------------------
procedure Test_Update_Publish_Date (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post_id", To_String (T.Post_Ident));
Request.Set_Parameter ("blog_id", Ident);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html");
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "POST_PUBLISHED");
Request.Set_Parameter ("format", "dotclear");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
Request.Set_Parameter ("publish-date", "");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Publish_Date;
-- ------------------------------
-- Test listing the blog posts.
-- ------------------------------
procedure Test_Admin_List_Posts (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html");
ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid");
end Test_Admin_List_Posts;
-- ------------------------------
-- Test listing the blog comments.
-- ------------------------------
procedure Test_Admin_List_Comments (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident,
"blog-list-comments.html");
ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply,
"Blog admin comments page is invalid");
end Test_Admin_List_Comments;
-- ------------------------------
-- Test getting the JSON blog stats (for graphs).
-- ------------------------------
procedure Test_Admin_Blog_Stats (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats",
"blog-stats.html");
ASF.Tests.Assert_Contains (T, "data", Reply,
"Blog admin stats page is invalid");
end Test_Admin_Blog_Stats;
end AWA.Blogs.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9aae2529def4af1bddaf8e78b74d75f66fe168e4
|
src/wiki-nodes.adb
|
src/wiki-nodes.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
-- procedure Append (Into : in out Document;
-- Node : in Node_Type_Access) is
-- begin
-- if Into.Current = null then
-- Append (Into.Nodes.Value.all, Node);
-- else
-- if Into.Current.Children = null then
-- Into.Current.Children := new Node_List;
-- Into.Current.Children.Current := Into.Current.Children.First'Access;
-- end if;
-- Append (Into.Current.Children.all, Node);
-- end if;
-- end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Into.Length);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- Finalize the node list to release the allocated memory.
overriding
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in out Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START then
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in out Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
-- ------------------------------
-- 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
-- Block : Node_List_Block_Access := Doc.Nodes.Value.First'Access;
-- begin
-- loop
-- for I in 1 .. Block.Last loop
-- Process (Block.List (I).all);
-- end loop;
-- Block := Block.Next;
-- exit when Block = null;
-- end loop;
-- end Iterate;
-- Append a node to the node list.
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access) is
begin
if Into.Is_Null then
Node_List_Refs.Ref (Into) := Node_List_Refs.Create;
end if;
end Append;
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type)) is
begin
if not List.Is_Null then
Iterate (List.Value, Process);
end if;
end Iterate;
--
-- overriding
-- procedure Initialize (Doc : in out Document) is
-- begin
-- -- Doc.Nodes := Node_List_Refs.Create;
-- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access;
-- end Initialize;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the tag node.
-- ------------------------------
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access) is
begin
if Into.Children = null then
Into.Children := new Node_List;
Into.Children.Current := Into.Children.First'Access;
end if;
Append (Into.Children.all, Node);
end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Into.Length);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- Finalize the node list to release the allocated memory.
overriding
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in out Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START then
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in out Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
-- ------------------------------
-- 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
-- Block : Node_List_Block_Access := Doc.Nodes.Value.First'Access;
-- begin
-- loop
-- for I in 1 .. Block.Last loop
-- Process (Block.List (I).all);
-- end loop;
-- Block := Block.Next;
-- exit when Block = null;
-- end loop;
-- end Iterate;
-- Append a node to the node list.
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access) is
begin
if Into.Is_Null then
Node_List_Refs.Ref (Into) := Node_List_Refs.Create;
end if;
end Append;
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type)) is
begin
if not List.Is_Null then
Iterate (List.Value, Process);
end if;
end Iterate;
--
-- overriding
-- procedure Initialize (Doc : in out Document) is
-- begin
-- -- Doc.Nodes := Node_List_Refs.Create;
-- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access;
-- end Initialize;
end Wiki.Nodes;
|
Implement the Append procedure
|
Implement the Append procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
24e833796295162f9086d9d2db0d3fd1383c4e51
|
src/asm-intrinsic/util-concurrent-counters.adb
|
src/asm-intrinsic/util-concurrent-counters.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
use Interfaces;
function Sync_Add_And_Fetch
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Add_And_Fetch,
External_Name => "__sync_add_and_fetch_4");
function Sync_Fetch_And_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, -1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
Value : Unsigned_32;
begin
Value := Sync_Add_And_Fetch (C.Value'Unrestricted_Access, -1);
Is_Zero := Value = 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
function Sync_Sub_And_Fetch (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Sub_And_Fetch,
External_Name => "__sync_sub_and_fetch_4");
function Sync_Fetch_And_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
procedure Sync_Sub (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Sub,
External_Name => "__sync_sub_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
use type Interfaces.Unsigned_32;
begin
Sync_Sub (C.Value'Unrestricted_Access, 1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
use type Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32;
begin
Value := Sync_Sub_And_Fetch (C.Value'Unrestricted_Access, 1);
Is_Zero := Value = 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
Fix and cleanup the atomic counters for ARM
|
Fix and cleanup the atomic counters for ARM
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
814c5bceb523a826dd44c9ec8562c1569a8ad128
|
src/asf-components-widgets-progress.adb
|
src/asf-components-widgets-progress.adb
|
-----------------------------------------------------------------------
-- components-widgets-progress -- Simple progress bar
-- Copyright (C) 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.Beans.Objects;
with ASF.Components.Base;
with ASF.Contexts.Writer;
with Ada.Text_IO.Editing;
package body ASF.Components.Widgets.Progress is
use Util.Beans.Objects;
package Formatter is
new Ada.Text_IO.Editing.Decimal_Output (Num => Progress_Type);
Format : constant Ada.Text_IO.Editing.Picture := Ada.Text_IO.Editing.To_Picture ("ZZ9.9");
function Get_Progress (UI : in UIProgressBar;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Progress_Type is
Value_Obj : constant Object := UI.Get_Attribute (Context, VALUE_ATTR_NAME);
Min_Obj : constant Object := UI.Get_Attribute (Context, MIN_VALUE_ATTR_NAME);
Max_Obj : constant Object := UI.Get_Attribute (Context, MAX_VALUE_ATTR_NAME);
Value : Long_Long_Float := To_Long_Long_Float (Value_Obj);
Min_Val : Long_Long_Float := 0.0;
Max_Val : Long_Long_Float := 0.0;
Div : Long_Long_Float;
begin
if not Is_Null (Min_Obj) then
Min_Val := To_Long_Long_Float (Min_Obj);
end if;
if not Is_Null (Max_Obj) then
Max_Val := To_Long_Long_Float (Max_Obj);
end if;
if Max_Val < Min_Val then
Base.Log_Error (UI, "progress min value ({0}) is < max value ({1})",
To_String (Min_Obj),
To_String (Max_Obj));
end if;
Div := Max_Val - Min_Val;
if Div <= 0.0 then
return 0.0;
end if;
Value := Value - Min_Val;
if Value >= Div then
return 100.0;
else
return Progress_Type (100.0 * Value / Div);
end if;
end Get_Progress;
-- ------------------------------
-- Render the tab start.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIProgressBar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Start_Element ("div");
declare
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
Progress : constant Progress_Type := UI.Get_Progress (Context);
Image : constant String := Formatter.Image (Progress, Format);
Pos : Positive := Image'First;
begin
while Pos < Image'Last and then Image (Pos) = ' ' loop
Pos := Pos + 1;
end loop;
if not UI.Is_Generated_Id then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
else
Writer.Write_Attribute ("class", "asf-progress");
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;
Writer.Start_Element ("span");
Writer.Write_Attribute ("class", "asf-progress-status");
Writer.Write_Attribute ("style",
"width:" & Image (Pos .. Image'Last) & "%");
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Render the tab close.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIProgressBar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.End_Element ("span");
Writer.End_Element ("div");
end if;
end Encode_End;
end ASF.Components.Widgets.Progress;
|
-----------------------------------------------------------------------
-- components-widgets-progress -- Simple progress bar
-- Copyright (C) 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.Beans.Objects;
with ASF.Components.Base;
with ASF.Contexts.Writer;
with Ada.Text_IO.Editing;
package body ASF.Components.Widgets.Progress is
use Util.Beans.Objects;
package Formatter is
new Ada.Text_IO.Editing.Decimal_Output (Num => Progress_Type);
Format : constant Ada.Text_IO.Editing.Picture := Ada.Text_IO.Editing.To_Picture ("ZZ9.9");
function Get_Progress (UI : in UIProgressBar;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Progress_Type is
Value_Obj : constant Object := UI.Get_Attribute (Context, VALUE_ATTR_NAME);
Min_Obj : constant Object := UI.Get_Attribute (Context, MIN_VALUE_ATTR_NAME);
Max_Obj : constant Object := UI.Get_Attribute (Context, MAX_VALUE_ATTR_NAME);
Value : Long_Long_Float := To_Long_Long_Float (Value_Obj);
Min_Val : Long_Long_Float := 0.0;
Max_Val : Long_Long_Float := 0.0;
Div : Long_Long_Float;
begin
if not Is_Null (Min_Obj) then
Min_Val := To_Long_Long_Float (Min_Obj);
end if;
if not Is_Null (Max_Obj) then
Max_Val := To_Long_Long_Float (Max_Obj);
end if;
if Max_Val < Min_Val then
Base.Log_Error (UI, "progress min value ({0}) is < max value ({1})",
To_String (Min_Obj),
To_String (Max_Obj));
end if;
Div := Max_Val - Min_Val;
if Div <= 0.0 then
return 0.0;
end if;
Value := Value - Min_Val;
if Value >= Div then
return 100.0;
else
return Progress_Type (100.0 * Value / Div);
end if;
end Get_Progress;
-- ------------------------------
-- Render the tab start.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIProgressBar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Start_Element ("div");
declare
Style : constant Object := UI.Get_Attribute (Context, "style");
Class : constant Object := UI.Get_Attribute (Context, "styleClass");
Title : constant Object := UI.Get_Attribute (Context, "title");
Progress : constant Progress_Type := UI.Get_Progress (Context);
Image : constant String := Formatter.Image (Progress, Format);
Pos : Positive := Image'First;
begin
while Pos < Image'Last and then Image (Pos) = ' ' loop
Pos := Pos + 1;
end loop;
if not UI.Is_Generated_Id then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
if not Is_Null (Class) then
Writer.Write_Attribute ("class", Class);
else
Writer.Write_Attribute ("class", "asf-progress-bar");
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;
Writer.Start_Element ("span");
Writer.Write_Attribute ("class", "asf-progress-status");
Writer.Write_Attribute ("style",
"width:" & Image (Pos .. Image'Last) & "%");
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Render the tab close.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIProgressBar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.End_Element ("span");
Writer.End_Element ("div");
end if;
end Encode_End;
end ASF.Components.Widgets.Progress;
|
Fix the progress bar CSS to use asf-progress-bar
|
Fix the progress bar CSS to use asf-progress-bar
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a0aea04aabc23f97a192e5478c47373866a27dfa
|
src/babel-strategies.adb
|
src/babel-strategies.adb
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Util.Log.Loggers;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
package body Babel.Strategies is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies");
-- ------------------------------
-- Allocate a buffer to read the file content.
-- ------------------------------
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is
Result : Babel.Files.Buffers.Buffer_Access;
begin
Strategy.Buffers.Get_Instance (Result);
return Result;
end Allocate_Buffer;
-- ------------------------------
-- Release the buffer that was allocated by Allocate_Buffer.
-- ------------------------------
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access) is
begin
Strategy.Buffers.Release (Buffer);
Buffer := null;
end Release_Buffer;
-- ------------------------------
-- Set the buffer pool to be used by Allocate_Buffer.
-- ------------------------------
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Strategy.Buffers := Buffers;
end Set_Buffers;
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Read_Store.Read (Path, Into.all);
end Read_File;
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Write_Store.Write (Path, Content.all);
end Write_File;
procedure Print_Sha (File : in Babel.Files.File_Type) is
Sha : constant String := Babel.Files.Get_SHA1 (File);
begin
Log.Info (Babel.Files.Get_Path (File) & " => " & Sha);
end Print_Sha;
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access) is
begin
Print_Sha (File);
Strategy.Write_File (File, Content);
Strategy.Release_Buffer (Content);
end Backup_File;
procedure Scan (Strategy : in out Strategy_Type;
Path : in String) is
begin
Strategy.Read_Store.Scan (Path, Strategy, Strategy.Filters.all);
while Strategy_Type'Class (Strategy).Has_Directory loop
declare
Path : constant String := Strategy_Type'Class (Strategy).Peek_Directory;
begin
Strategy.Read_Store.Scan (Path, Strategy, Strategy.Filters.all);
end;
end loop;
end Scan;
-- ------------------------------
-- Set the file filters that will be used when scanning the read store.
-- ------------------------------
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access) is
begin
Strategy.Filters := Filters;
end Set_Filters;
-- ------------------------------
-- Set the read and write stores that the strategy will use.
-- ------------------------------
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access) is
begin
Strategy.Read_Store := Read;
Strategy.Write_Store := Write;
end Set_Stores;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Util.Log.Loggers;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
package body Babel.Strategies is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies");
-- ------------------------------
-- Allocate a buffer to read the file content.
-- ------------------------------
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is
Result : Babel.Files.Buffers.Buffer_Access;
begin
Strategy.Buffers.Get_Instance (Result);
return Result;
end Allocate_Buffer;
-- ------------------------------
-- Release the buffer that was allocated by Allocate_Buffer.
-- ------------------------------
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access) is
begin
Strategy.Buffers.Release (Buffer);
Buffer := null;
end Release_Buffer;
-- ------------------------------
-- Set the buffer pool to be used by Allocate_Buffer.
-- ------------------------------
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Strategy.Buffers := Buffers;
end Set_Buffers;
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Read_Store.Read (Path, Into.all);
end Read_File;
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Write_Store.Write (Path, Content.all);
end Write_File;
procedure Print_Sha (File : in Babel.Files.File_Type) is
Sha : constant String := Babel.Files.Get_SHA1 (File);
begin
Log.Info (Babel.Files.Get_Path (File) & " => " & Sha);
end Print_Sha;
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access) is
begin
Print_Sha (File);
Strategy.Write_File (File, Content);
Strategy.Release_Buffer (Content);
end Backup_File;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class) is
Path : constant String := Babel.Files.Get_Path (Directory);
begin
Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all);
end Scan;
-- ------------------------------
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
-- ------------------------------
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class) is
procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is
begin
Babel.Files.Queues.Add_Directory (Queue, Directory);
end Append_Directory;
Dir : Babel.Files.Directory_Type;
begin
while Babel.Files.Queues.Has_Directory (Queue) loop
Babel.Files.Queues.Peek_Directory (Queue, Dir);
Container.Set_Directory (Dir);
Strategy_Type'Class (Strategy).Scan (Dir, Container);
Container.Each_Directory (Append_Directory'Access);
end loop;
end Scan;
-- ------------------------------
-- Set the file filters that will be used when scanning the read store.
-- ------------------------------
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access) is
begin
Strategy.Filters := Filters;
end Set_Filters;
-- ------------------------------
-- Set the read and write stores that the strategy will use.
-- ------------------------------
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access) is
begin
Strategy.Read_Store := Read;
Strategy.Write_Store := Write;
end Set_Stores;
end Babel.Strategies;
|
Implement the new Scan procedure
|
Implement the new Scan procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
3488b18e2a0dfb1392afd0336cd36fb40e181a25
|
src/babel-strategies.ads
|
src/babel-strategies.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
with Babel.Filters;
package Babel.Strategies is
type Strategy_Type is abstract limited new Babel.Files.File_Container with private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
function Peek_Directory (Strategy : in out Strategy_Type) return String is abstract;
procedure Scan (Strategy : in out Strategy_Type;
Path : in String);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Content : in Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Strategy_Type is abstract limited new Babel.Files.File_Container with record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
with Babel.Filters;
package Babel.Strategies is
type Strategy_Type is abstract limited new Babel.Files.File_Container with private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
function Peek_Directory (Strategy : in out Strategy_Type) return String is abstract;
procedure Scan (Strategy : in out Strategy_Type;
Path : in String);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File;
Content : in out Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Strategy_Type is abstract limited new Babel.Files.File_Container with record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Strategies;
|
Change the Content parameter of Backup_File as an in out parameter
|
Change the Content parameter of Backup_File as an in out parameter
|
Ada
|
apache-2.0
|
stcarrez/babel
|
16aea504ae063cf62a1eaf6402c9732477074f96
|
regtests/gen-artifacts-xmi-tests.adb
|
regtests/gen-artifacts-xmi-tests.adb
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Tag_Definition'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
-- Test searching an XMI Tag definition element by using its name.
procedure Test_Find_Tag_Definition (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Tag_Definition is
new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element,
Element_Type_Access => Tag_Definition_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
Tag : Tag_Definition_Element_Access;
begin
Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]",
Gen.Model.XMI.BY_NAME);
T.Assert (Tag /= null, "Tag definition not found");
end;
end Test_Find_Tag_Definition;
end Gen.Artifacts.XMI.Tests;
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Configs;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Tag_Definition'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
-- Test searching an XMI Tag definition element by using its name.
procedure Test_Find_Tag_Definition (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Tag_Definition is
new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element,
Element_Type_Access => Tag_Definition_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G);
declare
Tag : Tag_Definition_Element_Access;
begin
Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]",
Gen.Model.XMI.BY_NAME);
T.Assert (Tag /= null, "Tag definition not found");
end;
end Test_Find_Tag_Definition;
end Gen.Artifacts.XMI.Tests;
|
Update the unit test to use Read_Model
|
Update the unit test to use Read_Model
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3792a73ab7981d8b8fd46873cbbfbdd392b9aba5
|
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 Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER);
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;
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) 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 thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
-- 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);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER);
type Notice_Type is (N_PID_INFO,
N_PATH_INFO);
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) 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 thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
-- 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);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Define the Notice_Type type
|
Define the Notice_Type type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ffce08e912f94242cee1bdc3e5fb53afa7d1d82f
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- 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.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Converters.Dates;
with ASF.Tests;
with AWA.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- 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
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
if Add_Modules then
declare
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.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.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- 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.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Tests;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- 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
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
Remove dependencies to AWA modules
|
Remove dependencies to AWA modules
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
205f7f8f4abc18715c90fe1f4e2b9871619b8e8f
|
awa/plugins/awa-blogs/src/awa-blogs.ads
|
awa/plugins/awa-blogs/src/awa-blogs.ads
|
-----------------------------------------------------------------------
-- awa-blogs -- Blogs module
-- Copyright (C) 2011, 2014, 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.
-----------------------------------------------------------------------
-- = Blogs Module =
-- The `blogs` module is a small blog application which allows users
-- to publish articles. A user may own several blogs, each blog having
-- a name and its own base URI. Within a blog, the user may write articles
-- and publish them. Once published, the articles are visible to
-- anonymous users.
--
-- The `blogs` module uses several other modules:
--
-- * the [Counters Module] to track page display counter to a blog post,
-- * the [Tags Module] to associate one or several tags to a blog post,
-- * the [Comments Module] to allow users to write comments on a blog post,
-- * the [Images Module] to easily add images in blog post.
--
-- @include awa-blogs-modules.ads
-- @include awa-blogs-beans.ads
-- @include-bean blogs.xml
-- @include-bean blog-admin-post-list.xml
-- @include-bean blog-post-list.xml
-- @include-bean blog-comment-list.xml
-- @include-bean blog-list.xml
-- @include-bean blog-tags.xml
--
-- == Queries ==
-- @include-query blog-admin-post-list.xml
-- @include-query blog-post-list.xml
-- @include-query blog-comment-list.xml
-- @include-query blog-list.xml
-- @include-query blog-tags.xml
--
-- == Data model ==
-- [images/awa_blogs_model.png]
--
package AWA.Blogs is
pragma Pure;
end AWA.Blogs;
|
-----------------------------------------------------------------------
-- awa-blogs -- Blogs module
-- Copyright (C) 2011, 2014, 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.
-----------------------------------------------------------------------
-- = Blogs Module =
-- The `blogs` module is a small blog application which allows users
-- to publish articles. A user may own several blogs, each blog having
-- a name and its own base URI. Within a blog, the user may write articles
-- and publish them. Once published, the articles are visible to
-- anonymous users.
--
-- The `blogs` module uses several other modules:
--
-- * the [Counters Module] to track page display counter to a blog post,
-- * the [Tags Module] to associate one or several tags to a blog post,
-- * the [Comments Module] to allow users to write comments on a blog post,
-- * the [Images Module] to easily add images in blog post.
--
-- @include awa-blogs-modules.ads
-- @include awa-blogs-beans.ads
-- @include-bean blogs.xml
-- @include-bean blog-admin-post-list.xml
-- @include-bean blog-post-list.xml
-- @include-bean blog-comment-list.xml
-- @include-bean blog-list.xml
-- @include-bean blog-tags.xml
--
-- == Queries ==
-- @include-query blog-admin-post-list.xml
-- @include-query blog-post-list.xml
-- @include-query blog-comment-list.xml
-- @include-query blog-list.xml
-- @include-query blog-tags.xml
-- @include-query blog-images.xml
-- @include-query blog-images-info.xml
-- @include-query blog-stat.xml
--
-- == Data model ==
-- [images/awa_blogs_model.png]
--
package AWA.Blogs is
pragma Pure;
end AWA.Blogs;
|
Add more documentation
|
Add more documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
95400e4051342984737b720a2cf94e649d62620c
|
src/security-policies.ads
|
src/security-policies.ads
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
with Util.Serialize.Mappers;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Security Policies ==
-- The Security Policy defines and implements the set of security rules that specify
-- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains
-- the security policies. These policies are registered when an application starts,
-- before reading the policy configuration files.
--
-- [[images/PolicyModel.png]]
--
-- While the policy configuration files are processed, the policy instances that have been
-- registered will create a security controller and bind it to a given permission. After
-- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy
-- controllers which are associated with each permission defined by the application.
--
-- === Authenticated Permission ===
-- The `auth-permission` is a pre-defined permission that can be configured in the XML
-- configuration. Basically the permission is granted if the security context has a principal.
-- Otherwise the permission is denied. The permission is assigned a name and is declared
-- as follows:
--
-- <policy-rules>
-- <auth-permission>
-- <name>view-profile</name>
-- </auth-permission>
-- </policy-rules>
--
-- This example defines the `view-profile` permission.
--
-- === Grant Permission ===
-- The `grant-permission` is another pre-defined permission that gives the permission whatever
-- the security context. The permission is defined as follows:
--
-- <policy-rules>
-- <grant-permission>
-- <name>anonymous</name>
-- </grant-permission>
-- </policy-rules>
--
-- This example defines the `anonymous` permission.
--
-- @include security-policies-roles.ads
-- @include security-policies-urls.ads
--- @include security-controllers.ads
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is abstract new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String is abstract;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Mapper : in out Util.Serialize.Mappers.Processing) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Returns True if the security controller is defined for the given permission index.
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Manager : in out Policy_Manager;
Mapper : in out Util.Serialize.Mappers.Processing);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index := Policy_Index'First;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012, 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.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
with Util.Serialize.Mappers;
limited with Security.Controllers;
limited with Security.Contexts;
-- = Security Policies =
-- The Security Policy defines and implements the set of security rules that specify
-- how to protect the system or resources. The `Policy_Manager` maintains
-- the security policies. These policies are registered when an application starts,
-- before reading the policy configuration files.
--
-- [[images/PolicyModel.png]]
--
-- While the policy configuration files are processed, the policy instances that have been
-- registered will create a security controller and bind it to a given permission. After
-- successful initialization, the `Policy_Manager` contains a list of securiy
-- controllers which are associated with each permission defined by the application.
--
-- == Authenticated Permission ==
-- The `auth-permission` is a pre-defined permission that can be configured in the XML
-- configuration. Basically the permission is granted if the security context has a principal.
-- Otherwise the permission is denied. The permission is assigned a name and is declared
-- as follows:
--
-- <policy-rules>
-- <auth-permission>
-- <name>view-profile</name>
-- </auth-permission>
-- </policy-rules>
--
-- This example defines the `view-profile` permission.
--
-- == Grant Permission ==
-- The `grant-permission` is another pre-defined permission that gives the permission whatever
-- the security context. The permission is defined as follows:
--
-- <policy-rules>
-- <grant-permission>
-- <name>anonymous</name>
-- </grant-permission>
-- </policy-rules>
--
-- This example defines the `anonymous` permission.
--
-- @include security-policies-roles.ads
-- @include security-policies-urls.ads
--- @include security-controllers.ads
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is abstract new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String is abstract;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Mapper : in out Util.Serialize.Mappers.Processing) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Returns True if the security controller is defined for the given permission index.
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Manager : in out Policy_Manager;
Mapper : in out Util.Serialize.Mappers.Processing);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index := Policy_Index'First;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
693b36dba528d8e185eab179d58e3e482bfb075d
|
src/security-policies.ads
|
src/security-policies.ads
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
Fix indentation
|
Fix indentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
10076a1724b8bb2d8a18b40332bd791d704da9d2
|
testutil/ahven/ahven-text_runner.adb
|
testutil/ahven/ahven-text_runner.adb
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Ahven.Runner;
with Ahven.XML_Runner;
with Ahven.AStrings;
use Ada.Text_IO;
use Ada.Strings.Fixed;
package body Ahven.Text_Runner is
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
-- Local procedures
procedure Pad (Level : Natural);
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String);
procedure Print_Passes (Result : Result_Collection;
Level : Natural);
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False);
procedure Print_Log_File (Filename : String);
procedure Pad (Level : Natural) is
begin
for A in Integer range 1 .. Level loop
Put (" ");
end loop;
end Pad;
procedure Pad (Amount : in Natural;
Total : in out Natural) is
begin
for A in Natural range 1 .. Amount loop
Put (" ");
end loop;
Total := Total + Amount;
end Pad;
procedure Multiline_Pad (Input : String;
Level : Natural) is
begin
Pad (Level);
for A in Input'Range loop
Put (Input (A));
if (Input (A) = Ada.Characters.Latin_1.LF) and (A /= Input'Last) then
Pad (Level);
end if;
end loop;
end Multiline_Pad;
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String) is
use Ada.Strings;
Max_Output_Width : constant := 50;
Max_Result_Width : constant := 7;
Max_Time_Out_Width : constant := 12;
subtype Result_Size is Integer range 1 .. Max_Result_Width;
subtype Time_Out_Size is Integer range 1 .. Max_Time_Out_Width;
procedure Print_Text (Str : String; Total : in out Natural) is
begin
Put (Str);
Total := Total + Str'Length;
end Print_Text;
Msg : constant String := Get_Message (Info);
Result_Out : String (Result_Size) := (others => ' ');
Time_Out : String (Time_Out_Size) := (others => ' ');
Total_Text : Natural := 0;
begin
Pad (Level + 1, Total_Text);
Print_Text (Get_Routine_Name (Info), Total_Text);
if Msg'Length > 0 then
Print_Text (" - ", Total_Text);
Print_Text (Msg, Total_Text);
end if;
if Total_Text < Max_Output_Width then
Pad (Max_Output_Width - Total_Text, Total_Text);
end if;
-- If we know the name of the routine, we print it,
-- the result, and the execution time.
if Get_Routine_Name (Info)'Length > 0 then
Move (Source => Result,
Target => Result_Out,
Drop => Right,
Justify => Left,
Pad => ' ');
Move (Source => Duration'Image (Get_Execution_Time (Info)),
Target => Time_Out,
Drop => Right,
Justify => Right,
Pad => ' ');
Put (" " & Result_Out);
Put (" " & Time_Out & "s");
end if;
if Get_Long_Message (Info)'Length > 0 then
New_Line;
Multiline_Pad (Get_Long_Message (Info), Level + 2);
end if;
New_Line;
end Print_Test;
type Print_Child_Proc is access
procedure (Result : Result_Collection; Level : Natural);
type Child_Count_Proc is access
function (Result : Result_Collection) return Natural;
procedure Print_Children (Result : Result_Collection;
Level : Natural;
Action : Print_Child_Proc;
Count : Child_Count_Proc)
is
Child_Iter : Result_Collection_Cursor := First_Child (Result);
begin
loop
exit when not Is_Valid (Child_Iter);
if Count.all (Data (Child_Iter).all) > 0 then
Action.all (Data (Child_Iter).all, Level + 1);
end if;
Child_Iter := Next (Child_Iter);
end loop;
end Print_Children;
procedure Print_Statuses (Result : Result_Collection;
Level : Natural;
Start : Result_Info_Cursor;
Action : Print_Child_Proc;
Status : String;
Count : Child_Count_Proc;
Print_Log : Boolean) is
Position : Result_Info_Cursor := Start;
begin
if Length (Get_Test_Name (Result)) > 0 then
Pad (Level);
Put_Line (To_String (Get_Test_Name (Result)) & ":");
end if;
Test_Loop :
loop
exit Test_Loop when not Is_Valid (Position);
Print_Test (Data (Position), Level, Status);
if Print_Log and
(Length (Get_Output_File (Data (Position))) > 0) then
Print_Log_File (To_String (Get_Output_File (Data (Position))));
end if;
Position := Next (Position);
end loop Test_Loop;
Print_Children (Result => Result,
Level => Level,
Action => Action,
Count => Count);
end Print_Statuses;
--
-- Print all failures from the result collection
-- and then recurse into child collections.
--
procedure Print_Failures (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Failure (Result),
Action => Print_Failures'Access,
Status => "FAIL",
Count => Failure_Count'Access,
Print_Log => True);
end Print_Failures;
--
-- Print all skips from the result collection
-- and then recurse into child collections.
--
procedure Print_Skips (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Skipped (Result),
Action => Print_Skips'Access,
Status => "SKIPPED",
Count => Skipped_Count'Access,
Print_Log => True);
end Print_Skips;
--
-- Print all errors from the result collection
-- and then recurse into child collections.
--
procedure Print_Errors (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Error (Result),
Action => Print_Errors'Access,
Status => "ERROR",
Count => Error_Count'Access,
Print_Log => True);
end Print_Errors;
--
-- Print all passes from the result collection
-- and then recurse into child collections.
--
procedure Print_Passes (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Pass (Result),
Action => Print_Passes'Access,
Status => "PASS",
Count => Pass_Count'Access,
Print_Log => False);
end Print_Passes;
--
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False) is
begin
Put_Line ("Passed : " & Integer'Image (Pass_Count (Result)));
if Verbose then
Print_Passes (Result => Result, Level => 0);
end if;
New_Line;
if Skipped_Count (Result) > 0 then
Put_Line ("Skipped : " & Integer'Image (Skipped_Count (Result)));
Print_Skips (Result => Result, Level => 0);
New_Line;
end if;
if Failure_Count (Result) > 0 then
Put_Line ("Failed : " & Integer'Image (Failure_Count (Result)));
Print_Failures (Result => Result, Level => 0);
New_Line;
end if;
if Error_Count (Result) > 0 then
Put_Line ("Errors : " & Integer'Image (Error_Count (Result)));
Print_Errors (Result => Result, Level => 0);
end if;
end Report_Results;
procedure Print_Log_File (Filename : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
begin
Open (Handle, In_File, Filename);
begin
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line ("===== Output =======");
First := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
end if;
end loop;
-- The End_Error exception is sometimes raised.
exception
when Ada.IO_Exceptions.End_Error =>
null;
end;
Close (Handle);
if not First then
Put_Line ("====================");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
if Parameters.XML_Results (Args) then
XML_Runner.Report_Results
(Test_Results, Parameters.Result_Dir (Args));
else
Report_Results (Test_Results, Parameters.Verbose (Args));
end if;
end Do_Report;
procedure Run (Suite : in out Framework.Test'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.Text_Runner;
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Ahven.Runner;
with Ahven.XML_Runner;
with Ahven.AStrings;
use Ada.Text_IO;
use Ada.Strings.Fixed;
package body Ahven.Text_Runner is
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
-- Local procedures
procedure Pad (Level : Natural);
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String);
procedure Print_Passes (Result : Result_Collection;
Level : Natural);
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False);
procedure Print_Log_File (Filename : String);
procedure Pad (Level : Natural) is
begin
for A in Integer range 1 .. Level loop
Put (" ");
end loop;
end Pad;
procedure Pad (Amount : in Natural;
Total : in out Natural) is
begin
for A in Natural range 1 .. Amount loop
Put (" ");
end loop;
Total := Total + Amount;
end Pad;
procedure Multiline_Pad (Input : String;
Level : Natural) is
begin
Pad (Level);
for A in Input'Range loop
Put (Input (A));
if (Input (A) = Ada.Characters.Latin_1.LF) and (A /= Input'Last) then
Pad (Level);
end if;
end loop;
end Multiline_Pad;
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String) is
use Ada.Strings;
Max_Output_Width : constant := 50;
Max_Result_Width : constant := 7;
Max_Time_Out_Width : constant := 12;
subtype Result_Size is Integer range 1 .. Max_Result_Width;
subtype Time_Out_Size is Integer range 1 .. Max_Time_Out_Width;
procedure Print_Text (Str : String; Total : in out Natural) is
begin
Put (Str);
Total := Total + Str'Length;
end Print_Text;
Msg : constant String := Get_Message (Info);
Result_Out : String (Result_Size) := (others => ' ');
Time_Out : String (Time_Out_Size) := (others => ' ');
Total_Text : Natural := 0;
begin
Pad (Level + 1, Total_Text);
Print_Text (Get_Routine_Name (Info), Total_Text);
if Msg'Length > 0 then
Print_Text (" - ", Total_Text);
Print_Text (Msg, Total_Text);
end if;
if Total_Text < Max_Output_Width then
Pad (Max_Output_Width - Total_Text, Total_Text);
end if;
-- If we know the name of the routine, we print it,
-- the result, and the execution time.
if Get_Routine_Name (Info)'Length > 0 then
Move (Source => Result,
Target => Result_Out,
Drop => Right,
Justify => Left,
Pad => ' ');
Move (Source => Duration'Image (Get_Execution_Time (Info)),
Target => Time_Out,
Drop => Right,
Justify => Right,
Pad => ' ');
Put (" " & Result_Out);
Put (" " & Time_Out & "s");
end if;
if Get_Long_Message (Info)'Length > 0 then
New_Line;
Multiline_Pad (Get_Long_Message (Info), Level + 2);
end if;
New_Line;
end Print_Test;
type Print_Child_Proc is access
procedure (Result : Result_Collection; Level : Natural);
type Child_Count_Proc is access
function (Result : Result_Collection) return Natural;
procedure Print_Children (Result : Result_Collection;
Level : Natural;
Action : Print_Child_Proc;
Count : Child_Count_Proc)
is
Child_Iter : Result_Collection_Cursor := First_Child (Result);
begin
loop
exit when not Is_Valid (Child_Iter);
if Count.all (Data (Child_Iter).all) > 0 then
Action.all (Data (Child_Iter).all, Level + 1);
end if;
Child_Iter := Next (Child_Iter);
end loop;
end Print_Children;
procedure Print_Statuses (Result : Result_Collection;
Level : Natural;
Start : Result_Info_Cursor;
Action : Print_Child_Proc;
Status : String;
Count : Child_Count_Proc;
Print_Log : Boolean) is
Position : Result_Info_Cursor := Start;
begin
if Length (Get_Test_Name (Result)) > 0 then
Pad (Level);
Put_Line (To_String (Get_Test_Name (Result)) & ":");
end if;
Test_Loop :
loop
exit Test_Loop when not Is_Valid (Position);
Print_Test (Data (Position), Level, Status);
if Print_Log and
(Length (Get_Output_File (Data (Position))) > 0)
then
Print_Log_File (To_String (Get_Output_File (Data (Position))));
end if;
Position := Next (Position);
end loop Test_Loop;
Print_Children (Result => Result,
Level => Level,
Action => Action,
Count => Count);
end Print_Statuses;
--
-- Print all failures from the result collection
-- and then recurse into child collections.
--
procedure Print_Failures (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Failure (Result),
Action => Print_Failures'Access,
Status => "FAIL",
Count => Failure_Count'Access,
Print_Log => True);
end Print_Failures;
--
-- Print all skips from the result collection
-- and then recurse into child collections.
--
procedure Print_Skips (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Skipped (Result),
Action => Print_Skips'Access,
Status => "SKIPPED",
Count => Skipped_Count'Access,
Print_Log => True);
end Print_Skips;
--
-- Print all errors from the result collection
-- and then recurse into child collections.
--
procedure Print_Errors (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Error (Result),
Action => Print_Errors'Access,
Status => "ERROR",
Count => Error_Count'Access,
Print_Log => True);
end Print_Errors;
--
-- Print all passes from the result collection
-- and then recurse into child collections.
--
procedure Print_Passes (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Pass (Result),
Action => Print_Passes'Access,
Status => "PASS",
Count => Pass_Count'Access,
Print_Log => False);
end Print_Passes;
--
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False) is
begin
Put_Line ("Passed : " & Integer'Image (Pass_Count (Result)));
if Verbose then
Print_Passes (Result => Result, Level => 0);
end if;
New_Line;
if Skipped_Count (Result) > 0 then
Put_Line ("Skipped : " & Integer'Image (Skipped_Count (Result)));
Print_Skips (Result => Result, Level => 0);
New_Line;
end if;
if Failure_Count (Result) > 0 then
Put_Line ("Failed : " & Integer'Image (Failure_Count (Result)));
Print_Failures (Result => Result, Level => 0);
New_Line;
end if;
if Error_Count (Result) > 0 then
Put_Line ("Errors : " & Integer'Image (Error_Count (Result)));
Print_Errors (Result => Result, Level => 0);
end if;
end Report_Results;
procedure Print_Log_File (Filename : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
begin
Open (Handle, In_File, Filename);
begin
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line ("===== Output =======");
First := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
end if;
end loop;
-- The End_Error exception is sometimes raised.
exception
when Ada.IO_Exceptions.End_Error =>
null;
end;
Close (Handle);
if not First then
Put_Line ("====================");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
if Parameters.XML_Results (Args) then
XML_Runner.Report_Results
(Test_Results, Parameters.Result_Dir (Args));
else
Report_Results (Test_Results, Parameters.Verbose (Args));
end if;
end Do_Report;
procedure Run (Suite : in out Framework.Test'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.Text_Runner;
|
Fix style warning
|
Fix style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b431867a62dc6dc39625923bf27765b2a256eedb
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
end Wiki.Render.Html;
|
Replace Add_Quote by Render_Quote procedure
|
Replace Add_Quote by Render_Quote procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e86cf32c8fe177790694e4f4fe7ef515a0d002cf
|
src/wiki-render-text.adb
|
src/wiki-render-text.adb
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Filters.Html;
with Wiki.Helpers;
package body Wiki.Render.Text is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
Document.Output.Write (Wiki.Helpers.LF);
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Document : in out Text_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
pragma Unreferenced (Level);
begin
Document.Close_Paragraph;
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Writer.Write (Header);
Document.Add_Line_Break;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
Document.Writer.Write (Ada.Characters.Conversions.To_Wide_Wide_Character (ASCII.LF));
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
procedure Add_Paragraph (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural) is
begin
Document.Close_Paragraph;
for I in 1 .. Level loop
Document.Writer.Write (" ");
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
if Link /= Name then
Document.Writer.Write (Name);
end if;
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- 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) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
if Document.Empty_Line and Document.Indent_Level /= 0 then
for I in 1 .. Document.Indent_Level loop
Document.Writer.Write (' ');
end loop;
end if;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
pragma Unreferenced (Attributes);
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Empty_Line := True;
Document.Indent_Level := 4;
end if;
end Start_Element;
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String) is
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DL_TAG then
Document.Close_Paragraph;
Document.New_Line;
end if;
end End_Element;
-- 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) is
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Writer.Write (Node.Content);
Engine.Add_Line_Break;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Output.Write ("---------------------------------------------------------");
Engine.Add_Line_Break;
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
end case;
end Render;
--
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Filters.Html;
with Wiki.Helpers;
package body Wiki.Render.Text is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
Document.Output.Write (Wiki.Helpers.LF);
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
Document.Output.Write (Wiki.Helpers.LF);
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
procedure Add_Paragraph (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural) is
begin
Document.Close_Paragraph;
for I in 1 .. Level loop
Document.Writer.Write (" ");
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
if Link /= Name then
Document.Writer.Write (Name);
end if;
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- 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) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
if Document.Empty_Line and Document.Indent_Level /= 0 then
for I in 1 .. Document.Indent_Level loop
Document.Writer.Write (' ');
end loop;
end if;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
pragma Unreferenced (Attributes);
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Empty_Line := True;
Document.Indent_Level := 4;
end if;
end Start_Element;
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String) is
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DL_TAG then
Document.Close_Paragraph;
Document.New_Line;
end if;
end End_Element;
-- 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) is
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Output.Write (Node.Content);
Engine.Add_Line_Break;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Output.Write ("---------------------------------------------------------");
Engine.Add_Line_Break;
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
end case;
end Render;
--
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
Remove the Add_Header operation
|
Remove the Add_Header operation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
affc22b6cb08456291da9367006f8ed3ffbfef13
|
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.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.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document);
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;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams;
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);
-- Set the no-newline mode to produce a single line text (disabled by default).
procedure Set_No_Newline (Engine : in out Text_Renderer;
Enable : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document);
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;
No_Newline : Boolean := False;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Add Set_No_Newline to drop the newlines in the text document
|
Add Set_No_Newline to drop the newlines in the text document
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6ca95e247ce65e8d1c821afedd462b8f36e75d73
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with Security.Permissions;
-- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application.
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with Security.Permissions;
-- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application.
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
Add a parameter to setup the allow comment flag
|
Add a parameter to setup the allow comment flag
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
90d55a864d15ebe8eb8a851094887e2e63d7ad3a
|
awa/plugins/awa-images/src/awa-images-beans.adb
|
awa/plugins/awa-images/src/awa-images-beans.adb
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
package body AWA.Images.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Load the list of images associated with the current folder.
-- ------------------------------
overriding
procedure Load_Files (Storage : in Image_List_Bean) is
use AWA.Services;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Images.Models.Query_Image_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query);
Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True;
end Load_Files;
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "images" then
return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
-- if not List.Init_Flags (INIT_FOLDER) then
-- Load_Folder (List);
-- end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Create the Image_List_Bean bean instance.
-- ------------------------------
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
Object : constant Image_List_Bean_Access := new Image_List_Bean;
begin
Object.Module := AWA.Storages.Modules.Get_Storage_Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Image_List_Bean := Object.Image_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Image_List_Bean;
overriding
procedure Load (Into : in out Image_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
use type ADO.Identifier;
use type Ada.Containers.Count_Type;
use type Ada.Strings.Unbounded.Unbounded_String;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
if Into.Id = ADO.NO_IDENTIFIER then
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
return;
end if;
-- Get the list of versions associated with the wiki page.
Query.Set_Query (AWA.Images.Models.Query_Image_Info);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "file_id", Value => Into.Id);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
Into.Load (Session, Query);
end Load;
-- Create the Image_Bean bean instance.
function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Image_Bean_Access := new Image_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Image_Bean;
end AWA.Images.Beans;
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
package body AWA.Images.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Load the list of images associated with the current folder.
-- ------------------------------
overriding
procedure Load_Files (Storage : in Image_List_Bean) is
use AWA.Services;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Images.Models.Query_Image_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query);
Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True;
end Load_Files;
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "images" then
return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
-- if not List.Init_Flags (INIT_FOLDER) then
-- Load_Folder (List);
-- end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Create the Image_List_Bean bean instance.
-- ------------------------------
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
Object : constant Image_List_Bean_Access := new Image_List_Bean;
begin
Object.Module := AWA.Storages.Modules.Get_Storage_Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Image_List_Bean := Object.Image_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Image_List_Bean;
overriding
procedure Load (Into : in out Image_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
if Into.Id = ADO.NO_IDENTIFIER then
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
return;
end if;
-- Get the image information.
Query.Set_Query (AWA.Images.Models.Query_Image_Info);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "file_id", Value => Into.Id);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
Into.Load (Session, Query);
exception
when ADO.Objects.NOT_FOUND =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
-- ------------------------------
-- Create the Image_Bean bean instance.
-- ------------------------------
function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Image_Bean_Access := new Image_Bean;
begin
Object.Module := Module;
Object.Id := ADO.NO_IDENTIFIER;
return Object.all'Access;
end Create_Image_Bean;
end AWA.Images.Beans;
|
Fix Load operation to handle case where an image is not found or not visible for the user
|
Fix Load operation to handle case where an image is not found or not visible for the user
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8e66afe6bf6eba7ab4615a774b11027132f6a58d
|
tools/druss-commands.ads
|
tools/druss-commands.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Initialize;
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
end Druss.Commands;
|
Declare the Gateway_Command to run a command on one or all gateways based on the arguments
|
Declare the Gateway_Command to run a command on one or all gateways based on the arguments
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
b7a484236f16477692e05713ee9c76ce2fcd3efd
|
src/ado.ads
|
src/ado.ads
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Ada.Calendar;
with Util.Refs;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
-- An integer which can be null.
type Nullable_Integer is record
Value : Integer := 0;
Is_Null : Boolean := True;
end record;
-- A string which can be null.
type Nullable_String is record
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Null : Boolean := True;
end record;
-- A date which can be null.
type Nullable_Time is record
Value : Ada.Calendar.Time;
Is_Null : Boolean := True;
end record;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record
Data : Ada.Streams.Stream_Element_Array (1 .. Len);
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
-- Create a blob with an allocated buffer of <b>Size</b> bytes.
function Create_Blob (Size : in Natural) return Blob_Ref;
-- Create a blob initialized with the given data buffer.
function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref;
-- Create a blob initialized with the content from the file whose path is <b>Path</b>.
-- Raises an IO exception if the file does not exist.
function Create_Blob (Path : in String) return Blob_Ref;
-- Return a null blob.
function Null_Blob return Blob_Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
end ADO;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Ada.Calendar;
with Util.Refs;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
-- An integer which can be null.
type Nullable_Integer is record
Value : Integer := 0;
Is_Null : Boolean := True;
end record;
-- A string which can be null.
type Nullable_String is record
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Null : Boolean := True;
end record;
-- A date which can be null.
type Nullable_Time is record
Value : Ada.Calendar.Time;
Is_Null : Boolean := True;
end record;
type Nullable_Entity_Type is record
Value : Entity_Type;
Is_Null : Boolean := True;
end record;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record
Data : Ada.Streams.Stream_Element_Array (1 .. Len);
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
-- Create a blob with an allocated buffer of <b>Size</b> bytes.
function Create_Blob (Size : in Natural) return Blob_Ref;
-- Create a blob initialized with the given data buffer.
function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref;
-- Create a blob initialized with the content from the file whose path is <b>Path</b>.
-- Raises an IO exception if the file does not exist.
function Create_Blob (Path : in String) return Blob_Ref;
-- Return a null blob.
function Null_Blob return Blob_Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
end ADO;
|
Declare the Nullable_Entity_Type type
|
Declare the Nullable_Entity_Type type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
a6d0d0e50985191b45d69b94eb4fefe731946ef2
|
src/util-dates.ads
|
src/util-dates.ads
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;
with Ada.Calendar.Time_Zones;
-- = Date Utilities =
-- The `Util.Dates` package provides various date utilities to help in formatting and parsing
-- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and
-- other packages by implementing specific formatting and parsing.
--
-- == Date Operations ==
-- Several operations allow to compute:
--
-- * The start of the day (0:00),
-- * The end of the day (24:00),
-- * The start of the week,
-- * The end of the week,
-- * The start of the month,
-- * The end of the month
--
-- @include util-dates-rfc7231.ads
-- @include util-dates-iso8601.ads
-- @include util-dates-formats.ads
package Util.Dates is
-- The Unix equivalent of 'struct tm'.
type Date_Record is record
Date : Ada.Calendar.Time;
Year : Ada.Calendar.Year_Number;
Month : Ada.Calendar.Month_Number;
Month_Day : Ada.Calendar.Day_Number;
Day : Ada.Calendar.Formatting.Day_Name;
Hour : Ada.Calendar.Formatting.Hour_Number;
Minute : Ada.Calendar.Formatting.Minute_Number;
Second : Ada.Calendar.Formatting.Second_Number;
Sub_Second : Ada.Calendar.Formatting.Second_Duration;
Time_Zone : Ada.Calendar.Time_Zones.Time_Offset;
Leap_Second : Boolean;
end record;
-- 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);
-- Returns true if the given year is a leap year.
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean;
-- 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;
-- 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;
-- Get a time representing the given date at 00:00:00.
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- Get a time representing the given date at 23:59:59.
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
end Util.Dates;
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;
with Ada.Calendar.Time_Zones;
-- = Date Utilities =
-- The `Util.Dates` package provides various date utilities to help in formatting and parsing
-- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and
-- other packages by implementing specific formatting and parsing.
--
-- == Date Operations ==
-- Several operations allow to compute from a given date:
--
-- * `Get_Day_Start`: The start of the day (0:00),
-- * `Get_Day_End`: The end of the day (23:59:59),
-- * `Get_Week_Start`: The start of the week,
-- * `Get_Week_End`: The end of the week,
-- * `Get_Month_Start`: The start of the month,
-- * `Get_Month_End`: The end of the month
--
-- The `Date_Record` type represents a date in a split format allowing
-- to access easily the day, month, hour and other information.
--
-- Now : Ada.Calendar.Time := Ada.Calendar.Clock;
-- Week_Start : Ada.Calendar.Time := Get_Week_Start (Now);
-- Week_End : Ada.Calendar.Time := Get_Week_End (Now);
--
-- @include util-dates-rfc7231.ads
-- @include util-dates-iso8601.ads
-- @include util-dates-formats.ads
package Util.Dates is
-- The Unix equivalent of 'struct tm'.
type Date_Record is record
Date : Ada.Calendar.Time;
Year : Ada.Calendar.Year_Number;
Month : Ada.Calendar.Month_Number;
Month_Day : Ada.Calendar.Day_Number;
Day : Ada.Calendar.Formatting.Day_Name;
Hour : Ada.Calendar.Formatting.Hour_Number;
Minute : Ada.Calendar.Formatting.Minute_Number;
Second : Ada.Calendar.Formatting.Second_Number;
Sub_Second : Ada.Calendar.Formatting.Second_Duration;
Time_Zone : Ada.Calendar.Time_Zones.Time_Offset;
Leap_Second : Boolean;
end record;
-- 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);
-- Returns true if the given year is a leap year.
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean;
-- 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;
-- 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;
-- Get a time representing the given date at 00:00:00.
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- Get a time representing the given date at 23:59:59.
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
-- 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;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time;
end Util.Dates;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
da1d239ee3aca3044ced785191fed3a553046f2d
|
ARM/STM32/drivers/dma2d/stm32-dma2d.ads
|
ARM/STM32/drivers/dma2d/stm32-dma2d.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 the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System;
with Ada.Unchecked_Conversion;
package STM32.DMA2D is
type DMA2D_Color is record
Alpha : Byte;
Red : Byte;
Green : Byte;
Blue : Byte;
end record;
for DMA2D_Color use record
Blue at 0 range 0 .. 7;
Green at 1 range 0 .. 7;
Red at 2 range 0 .. 7;
Alpha at 3 range 0 .. 7;
end record;
Black : constant DMA2D_Color := (255, 0, 0, 0);
White : constant DMA2D_Color := (255, 255, 255, 255);
Transparent : constant DMA2D_Color := (others => 0);
-- This bit is set and cleared by software. It cannot be modified
-- while a transfer is ongoing.
type DMA2D_MODE is
(
-- Memory-to-memory (FG fetch only)
M2M,
-- Memory-to-memory with PFC (FG fetch only with FG PFC active)
M2M_PFC,
-- Memory-to-memory with blending (FG and BG fetch with PFC and
-- blending)
M2M_BLEND,
-- Register-to-memory (no FG nor BG, only output stage active)
R2M
);
for DMA2D_MODE'Size use 2;
-- Configuration Error Interrupt Enable
type DMA2D_FLAG is
(Disable,
Enable);
-- Abort
-- This bit can be used to abort the current transfer. This bit is
-- set by software and is automatically reset by hardware when the
-- START bit is reset.
type DMA2D_ABORT is
(
-- 0: No transfer abort requested
Not_Requested,
-- 1: Transfer abort requested
Requested);
-- Suspend
-- This bit can be used to suspend the current transfer. This bit
-- is set and reset by software. It is automatically reset by
-- hardware when the START bit is reset.
type DMA2D_SUSPEND is
(
-- Transfer not suspended
Not_Suspended,
-- Transfer suspended
Supended);
-- Start
-- This bit can be used to launch the DMA2D according to the
-- parameters loaded in the various configuration registers. This
-- bit is automatically reset by the following events:
-- - At the end of the transfer
-- - When the data transfer is aborted by the user application by
-- setting the ABORT bit in DMA2D_CR
-- - When a data transfer error occurs
-- - When the data transfer has not started due to a configuration
-- error or another transfer operation already ongoing (automatic
-- CLUT loading)
type DMA2D_START is
(Not_Started,
Start);
-- These bits defines the color format
type DMA2D_Color_Mode is
(ARGB8888,
RGB888,
RGB565,
ARGB1555,
ARGB4444,
L8,
AL44,
AL88,
L4,
A8,
A4) with Size => 4;
subtype DMA2D_CLUT_Color_Mode is DMA2D_Color_Mode range
ARGB8888 .. RGB888;
subtype DMA2D_Dst_Color_Mode is DMA2D_Color_Mode range ARGB8888 .. ARGB4444;
subtype Foreground_Color_Mode is DMA2D_Color_Mode;
subtype Background_Color_Mode is DMA2D_Color_Mode;
subtype Output_Color_Mode is DMA2D_Color_Mode range ARGB8888 .. ARGB4444;
-- function Bytes_Per_Pixel (CM : DMA2D_Color_Mode) return Positive
-- is (case CM is
-- when ARGB8888 => 4,
-- when RGB888 => 3,
-- when others => 2);
-- Alpha mode
-- 00: No modification of the foreground image alpha channel value
-- 01: Replace original foreground image alpha channel value by ALPHA[7:0]
-- 10: Replace original foreground image alpha channel value by ALPHA[7:0]
-- multiplied with original alpha channel value
-- other configurations are meaningless
type DMA2D_AM is
(NO_MODIF,
REPLACE,
MULTIPLY);
for DMA2D_AM'Size use 2;
procedure DMA2D_DeInit;
type DMA2D_Sync_Procedure is access procedure;
procedure DMA2D_Init
(Init : DMA2D_Sync_Procedure;
Wait : DMA2D_Sync_Procedure);
type DMA2D_Buffer (Color_Mode : DMA2D_Color_Mode := ARGB8888) is record
Addr : System.Address;
Width : Natural;
Height : Natural;
case Color_Mode is
when L8 | L4 =>
CLUT_Color_Mode : DMA2D_CLUT_Color_Mode;
CLUT_Addr : System.Address;
when others =>
null;
end case;
end record;
Null_Buffer : constant DMA2D_Buffer :=
(Addr => System.Null_Address,
Width => 0,
Height => 0,
Color_Mode => DMA2D_Color_Mode'First);
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : UInt32;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : UInt32;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel_Blend
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Draw_Rect
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Copy_Rect
(Src_Buffer : DMA2D_Buffer;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : DMA2D_Buffer;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean := False)
with Pre => Dst_Buffer.Color_Mode in Output_Color_Mode;
-- Copy a rectangular area from Src to Dst
-- If Blend is set, then the rectangle will be merged with the destination
-- area, taking into account the opacity of the source. Else, it is simply
-- copied.
--
-- if Bg_Buffer is not Null_Buffer, then the copy will be performed in
-- blend mode: Bg_Buffer and Src_Buffer are combined first and then copied
-- to Dst_Buffer.
procedure DMA2D_Draw_Vertical_Line
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Height : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Draws a vertical line
procedure DMA2D_Draw_Horizontal_Line
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Draws a vertical line
procedure DMA2D_Wait_Transfer;
-- Makes sure the DMA2D transfers are done
private
function As_UInt3 is new Ada.Unchecked_Conversion
(DMA2D_Dst_Color_Mode, UInt3);
function As_UInt4 is new Ada.Unchecked_Conversion
(DMA2D_Color_Mode, UInt4);
end STM32.DMA2D;
|
------------------------------------------------------------------------------
-- --
-- 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 the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System;
with Ada.Unchecked_Conversion;
package STM32.DMA2D is
type DMA2D_Color is record
Alpha : Byte;
Red : Byte;
Green : Byte;
Blue : Byte;
end record;
for DMA2D_Color use record
Blue at 0 range 0 .. 7;
Green at 1 range 0 .. 7;
Red at 2 range 0 .. 7;
Alpha at 3 range 0 .. 7;
end record;
Black : constant DMA2D_Color := (255, 0, 0, 0);
White : constant DMA2D_Color := (255, 255, 255, 255);
Transparent : constant DMA2D_Color := (others => 0);
-- This bit is set and cleared by software. It cannot be modified
-- while a transfer is ongoing.
type DMA2D_MODE is
(
-- Memory-to-memory (FG fetch only)
M2M,
-- Memory-to-memory with PFC (FG fetch only with FG PFC active)
M2M_PFC,
-- Memory-to-memory with blending (FG and BG fetch with PFC and
-- blending)
M2M_BLEND,
-- Register-to-memory (no FG nor BG, only output stage active)
R2M
);
for DMA2D_MODE'Size use 2;
-- Configuration Error Interrupt Enable
type DMA2D_FLAG is
(Disable,
Enable);
-- Abort
-- This bit can be used to abort the current transfer. This bit is
-- set by software and is automatically reset by hardware when the
-- START bit is reset.
type DMA2D_ABORT is
(
-- 0: No transfer abort requested
Not_Requested,
-- 1: Transfer abort requested
Requested);
-- Suspend
-- This bit can be used to suspend the current transfer. This bit
-- is set and reset by software. It is automatically reset by
-- hardware when the START bit is reset.
type DMA2D_SUSPEND is
(
-- Transfer not suspended
Not_Suspended,
-- Transfer suspended
Supended);
-- Start
-- This bit can be used to launch the DMA2D according to the
-- parameters loaded in the various configuration registers. This
-- bit is automatically reset by the following events:
-- - At the end of the transfer
-- - When the data transfer is aborted by the user application by
-- setting the ABORT bit in DMA2D_CR
-- - When a data transfer error occurs
-- - When the data transfer has not started due to a configuration
-- error or another transfer operation already ongoing (automatic
-- CLUT loading)
type DMA2D_START is
(Not_Started,
Start);
-- These bits defines the color format
type DMA2D_Color_Mode is
(ARGB8888,
RGB888,
RGB565,
ARGB1555,
ARGB4444,
L8,
AL44,
AL88,
L4,
A8,
A4) with Size => 4;
subtype DMA2D_CLUT_Color_Mode is DMA2D_Color_Mode range
ARGB8888 .. RGB888;
subtype DMA2D_Dst_Color_Mode is DMA2D_Color_Mode range ARGB8888 .. ARGB4444;
subtype Foreground_Color_Mode is DMA2D_Color_Mode;
subtype Background_Color_Mode is DMA2D_Color_Mode;
subtype Output_Color_Mode is DMA2D_Color_Mode range ARGB8888 .. ARGB4444;
-- function Bytes_Per_Pixel (CM : DMA2D_Color_Mode) return Positive
-- is (case CM is
-- when ARGB8888 => 4,
-- when RGB888 => 3,
-- when others => 2);
-- Alpha mode
-- 00: No modification of the foreground image alpha channel value
-- 01: Replace original foreground image alpha channel value by ALPHA[7:0]
-- 10: Replace original foreground image alpha channel value by ALPHA[7:0]
-- multiplied with original alpha channel value
-- other configurations are meaningless
type DMA2D_AM is
(NO_MODIF,
REPLACE,
MULTIPLY);
for DMA2D_AM'Size use 2;
procedure DMA2D_DeInit;
type DMA2D_Sync_Procedure is access procedure;
procedure DMA2D_Init
(Init : DMA2D_Sync_Procedure;
Wait : DMA2D_Sync_Procedure);
type DMA2D_Buffer (Color_Mode : DMA2D_Color_Mode := ARGB8888) is record
Addr : System.Address;
Width : Natural;
Height : Natural;
case Color_Mode is
when L8 | L4 =>
CLUT_Color_Mode : DMA2D_CLUT_Color_Mode;
CLUT_Addr : System.Address;
when others =>
null;
end case;
end record;
Null_Buffer : constant DMA2D_Buffer :=
(Addr => System.Null_Address,
Width => 0,
Height => 0,
Color_Mode => DMA2D_Color_Mode'First);
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : UInt32;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : UInt32;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel_Blend
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Draw_Rect
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Copy_Rect
(Src_Buffer : DMA2D_Buffer;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : DMA2D_Buffer;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean := False)
with Pre => Dst_Buffer.Color_Mode in Output_Color_Mode;
-- Copy a rectangular area from Src to Dst
-- If Blend is set, then the rectangle will be merged with the destination
-- area, taking into account the opacity of the source. Else, it is simply
-- copied.
--
-- if Bg_Buffer is not Null_Buffer, then the copy will be performed in
-- blend mode: Bg_Buffer and Src_Buffer are combined first and then copied
-- to Dst_Buffer.
procedure DMA2D_Draw_Vertical_Line
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Height : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Draws a vertical line
procedure DMA2D_Draw_Horizontal_Line
(Buffer : DMA2D_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Synchronous : Boolean := False)
with Pre => Buffer.Color_Mode in Output_Color_Mode;
-- Draws a vertical line
procedure DMA2D_Wait_Transfer
with Inline_Always;
-- Makes sure the DMA2D transfers are done
private
function As_UInt3 is new Ada.Unchecked_Conversion
(DMA2D_Dst_Color_Mode, UInt3);
function As_UInt4 is new Ada.Unchecked_Conversion
(DMA2D_Color_Mode, UInt4);
end STM32.DMA2D;
|
make sure DMA2D_Wait_Transfer is always inline.
|
Minor: make sure DMA2D_Wait_Transfer is always inline.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library
|
f9334eb228f28255507fb343eb28d0ec5e40acb2
|
src/wiki-nodes.adb
|
src/wiki-nodes.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the tag node.
-- ------------------------------
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access) is
begin
if Into.Children = null then
Into.Children := new Node_List;
Into.Children.Current := Into.Children.First'Access;
end if;
Append (Into.Children.all, Node);
end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Into.Length);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- ------------------------------
-- Finalize the node list to release the allocated memory.
-- ------------------------------
overriding
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START then
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access) is
begin
if Into.Is_Null then
Node_List_Refs.Ref (Into) := Node_List_Refs.Create;
Into.Value.Current := Into.Value.First'Access;
end if;
Append (Into.Value.all, Node);
end Append;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type)) is
begin
if not List.Is_Null then
Iterate (List.Value, Process);
end if;
end Iterate;
-- ------------------------------
-- Returns True if the list reference is empty.
-- ------------------------------
function Is_Empty (List : in Node_List_Ref) return Boolean is
begin
return List.Is_Null;
end Is_Empty;
-- ------------------------------
-- Get the number of nodes in the list.
-- ------------------------------
function Length (List : in Node_List_Ref) return Natural is
begin
if List.Is_Null then
return 0;
else
return List.Value.Length;
end if;
end Length;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the tag node.
-- ------------------------------
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access) is
begin
if Into.Children = null then
Into.Children := new Node_List;
Into.Children.Current := Into.Children.First'Access;
end if;
Append (Into.Children.all, Node);
end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Into.Length);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- ------------------------------
-- Finalize the node list to release the allocated memory.
-- ------------------------------
overriding
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then
Finalize (Block.List (I).Children.all);
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access) is
begin
if Into.Is_Null then
Node_List_Refs.Ref (Into) := Node_List_Refs.Create;
Into.Value.Current := Into.Value.First'Access;
end if;
Append (Into.Value.all, Node);
end Append;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type)) is
begin
if not List.Is_Null then
Iterate (List.Value, Process);
end if;
end Iterate;
-- ------------------------------
-- Returns True if the list reference is empty.
-- ------------------------------
function Is_Empty (List : in Node_List_Ref) return Boolean is
begin
return List.Is_Null;
end Is_Empty;
-- ------------------------------
-- Get the number of nodes in the list.
-- ------------------------------
function Length (List : in Node_List_Ref) return Natural is
begin
if List.Is_Null then
return 0;
else
return List.Value.Length;
end if;
end Length;
end Wiki.Nodes;
|
Fix finalization of Node_List
|
Fix finalization of Node_List
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c63744af0f31f7d491b2abe67a1d288b4d14215d
|
awa/src/awa-commands-drivers.adb
|
awa/src/awa-commands-drivers.adb
|
-----------------------------------------------------------------------
-- awa-commands-drivers -- Driver for AWA commands for server or admin tool
-- 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.Command_Line;
with Servlet.Core;
package body AWA.Commands.Drivers is
use Ada.Strings.Unbounded;
function "-" (Message : in String) return String is (Message);
Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
AWA.Commands.Setup (Config, Context);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Application_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Define_Switch (Config => Config,
Output => Command.Application_Name'Access,
Switch => "-a:",
Long_Switch => "--application=",
Argument => "NAME",
Help => -("Defines the name or URI of the application"));
AWA.Commands.Setup (Config, Context);
end Setup;
function Is_Application (Command : in Application_Command_Type;
URI : in String) return Boolean is
begin
return Command.Application_Name.all = URI;
end Is_Application;
overriding
procedure Execute (Command : in out Application_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Find (URI : in String;
Application : in Servlet.Core.Servlet_Registry_Access);
Count : Natural := 0;
Selected : AWA.Applications.Application_Access;
App_Name : Unbounded_String;
procedure Find (URI : in String;
Application : in Servlet.Core.Servlet_Registry_Access) is
begin
if Application.all in AWA.Applications.Application'Class then
if Command.Is_Application (URI) then
App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last));
Selected := AWA.Applications.Application'Class (Application.all)'Unchecked_Access;
Count := Count + 1;
elsif Command.Application_Name'Length = 0 then
App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last));
Selected := AWA.Applications.Application'Class (Application.all)'Unchecked_Access;
Count := Count + 1;
end if;
end if;
end Find;
begin
WS.Iterate (Find'Access);
if Count /= 1 then
Context.Console.Notice (N_ERROR, -("No application found"));
return;
end if;
Configure (Selected.all, To_String (App_Name), Context);
Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context);
end Execute;
-- ------------------------------
-- Print the command usage.
-- ------------------------------
procedure Usage (Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
GC.Display_Help (Context.Command_Config);
if Name'Length > 0 then
Driver.Usage (Args, Context, Name);
end if;
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end Usage;
-- ------------------------------
-- Execute the command with its arguments.
-- ------------------------------
procedure Execute (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
Driver.Execute (Name, Args, Context);
end Execute;
procedure Run (Context : in out Context_Type;
Arguments : out Util.Commands.Dynamic_Argument_List) is
begin
GC.Getopt (Config => Context.Command_Config);
Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument);
--if Context.Debug or Context.Verbose or Context.Dump then
-- AKT.Configure_Logs (Debug => Context.Debug,
-- Dump => Context.Dump,
-- Verbose => Context.Verbose);
--end if;
Context.Load_Configuration;
declare
Cmd_Name : constant String := Arguments.Get_Command_Name;
begin
if Cmd_Name'Length = 0 then
Context.Console.Notice (N_ERROR, -("Missing command name to execute."));
Usage (Arguments, Context);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
Execute (Cmd_Name, Arguments, Context);
exception
when GNAT.Command_Line.Invalid_Parameter =>
Context.Console.Notice (N_ERROR, -("Missing option parameter"));
raise Error;
end;
end Run;
begin
Driver.Add_Command ("help",
-("print some help"),
Help_Command'Access);
end AWA.Commands.Drivers;
|
-----------------------------------------------------------------------
-- awa-commands-drivers -- Driver for AWA commands for server or admin tool
-- 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.Command_Line;
with Servlet.Core;
package body AWA.Commands.Drivers is
use Ada.Strings.Unbounded;
use AWA.Applications;
function "-" (Message : in String) return String is (Message);
Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
AWA.Commands.Setup_Command (Config, Context);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Application_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Define_Switch (Config => Config,
Output => Command.Application_Name'Access,
Switch => "-a:",
Long_Switch => "--application=",
Argument => "NAME",
Help => -("Defines the name or URI of the application"));
AWA.Commands.Setup_Command (Config, Context);
end Setup;
function Is_Application (Command : in Application_Command_Type;
URI : in String) return Boolean is
begin
return Command.Application_Name.all = URI;
end Is_Application;
overriding
procedure Execute (Command : in out Application_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Find (URI : in String;
App : in Servlet.Core.Servlet_Registry_Access);
Count : Natural := 0;
Selected : Application_Access;
App_Name : Unbounded_String;
procedure Find (URI : in String;
App : in Servlet.Core.Servlet_Registry_Access) is
begin
if Application.all in Application'Class then
if Command.Is_Application (URI) then
App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last));
Selected := Application'Class (Application.all)'Unchecked_Access;
Count := Count + 1;
elsif Command.Application_Name'Length = 0 then
App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last));
Selected := Application'Class (Application.all)'Unchecked_Access;
Count := Count + 1;
end if;
end if;
end Find;
begin
WS.Iterate (Find'Access);
if Count /= 1 then
Context.Console.Notice (N_ERROR, -("No application found"));
return;
end if;
Configure (Selected.all, To_String (App_Name), Context);
Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context);
end Execute;
-- ------------------------------
-- Print the command usage.
-- ------------------------------
procedure Usage (Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
GC.Display_Help (Context.Command_Config);
if Name'Length > 0 then
Driver.Usage (Args, Context, Name);
end if;
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end Usage;
-- ------------------------------
-- Execute the command with its arguments.
-- ------------------------------
procedure Execute (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
Driver.Execute (Name, Args, Context);
end Execute;
procedure Run (Context : in out Context_Type;
Arguments : out Util.Commands.Dynamic_Argument_List) is
begin
GC.Getopt (Config => Context.Command_Config);
Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument);
--if Context.Debug or Context.Verbose or Context.Dump then
-- AKT.Configure_Logs (Debug => Context.Debug,
-- Dump => Context.Dump,
-- Verbose => Context.Verbose);
--end if;
Context.Load_Configuration;
declare
Cmd_Name : constant String := Arguments.Get_Command_Name;
begin
if Cmd_Name'Length = 0 then
Context.Console.Notice (N_ERROR, -("Missing command name to execute."));
Usage (Arguments, Context);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
Execute (Cmd_Name, Arguments, Context);
exception
when GNAT.Command_Line.Invalid_Parameter =>
Context.Console.Notice (N_ERROR, -("Missing option parameter"));
raise Error;
end;
end Run;
begin
Driver.Add_Command ("help",
-("print some help"),
Help_Command'Access);
end AWA.Commands.Drivers;
|
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
|
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4c27d41cdd693587ee572a20e5754824818e1bef
|
src/sys/serialize/util-serialize-io-csv.adb
|
src/sys/serialize/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Ada.Containers;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
Fix compilation with GNAT 2021: add missing with Ada.Containers clause
|
Fix compilation with GNAT 2021: add missing with Ada.Containers clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
05f621178220e8c37dd56f5c991dce84674b1308
|
awa/src/awa-applications-configs.adb
|
awa/src/awa-applications-configs.adb
|
-----------------------------------------------------------------------
-- awa-applications-configs -- Read application configuration files
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Files;
with Util.Log.Loggers;
with ASF.Contexts.Faces;
with ASF.Applications.Main.Configs;
with Security.Policies;
with AWA.Events.Configs;
with AWA.Services.Contexts;
package body AWA.Applications.Configs is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs");
-- ------------------------------
-- XML reader configuration. By instantiating this generic package, the XML parser
-- gets initialized to read the configuration for servlets, filters, managed beans,
-- permissions, events and other configuration elements.
-- ------------------------------
package body Reader_Config is
App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access;
package Bean_Config is
new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access,
Context.all'Access,
Override_Context);
package Event_Config is
new AWA.Events.Configs.Reader_Config (Reader => Reader,
Manager => App.Events'Unchecked_Access,
Context => Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Event_Config);
end Reader_Config;
-- ------------------------------
-- Read the application configuration file and configure the application
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean) is
Reader : Util.Serialize.IO.XML.Parser;
Ctx : AWA.Services.Contexts.Service_Context;
Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager;
begin
Log.Info ("Reading application configuration file {0}", File);
Ctx.Set_Context (App'Unchecked_Access, null);
declare
package Config is new Reader_Config (Reader, App'Unchecked_Access, Context,
Override_Context);
pragma Warnings (Off, Config);
begin
Sec.Prepare_Config (Reader);
-- Initialize the parser with the module configuration mappers (if any).
Initialize_Parser (App, Reader);
if Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end;
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
-- ------------------------------
-- Get the configuration path for the application name.
-- The configuration path is search from:
-- o the current directory,
-- o the 'config' directory,
-- o the Dynamo installation directory in share/dynamo
-- ------------------------------
function Get_Config_Path (Name : in String) return String is
use Ada.Strings.Unbounded;
use Ada.Directories;
Command : constant String := Ada.Command_Line.Command_Name;
Path : constant String := Ada.Directories.Containing_Directory (Command);
Dir : constant String := Containing_Directory (Path);
Paths : Ada.Strings.Unbounded.Unbounded_String;
begin
Append (Paths, ".;");
Append (Paths, Util.Files.Compose (Dir, "config"));
Append (Paths, ";");
Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name));
return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths));
end Get_Config_Path;
end AWA.Applications.Configs;
|
-----------------------------------------------------------------------
-- awa-applications-configs -- Read application configuration files
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Files;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with ASF.Contexts.Faces;
with ASF.Applications.Main.Configs;
with Security.Policies;
with AWA.Events.Configs;
with AWA.Services.Contexts;
package body AWA.Applications.Configs is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs");
-- ------------------------------
-- XML reader configuration. By instantiating this generic package, the XML parser
-- gets initialized to read the configuration for servlets, filters, managed beans,
-- permissions, events and other configuration elements.
-- ------------------------------
package body Reader_Config is
App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access;
package Bean_Config is
new ASF.Applications.Main.Configs.Reader_Config (Mapper, App_Access,
Context.all'Access,
Override_Context);
package Event_Config is
new AWA.Events.Configs.Reader_Config (Mapper => Mapper,
Manager => App.Events'Unchecked_Access,
Context => Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Event_Config);
end Reader_Config;
-- ------------------------------
-- Read the application configuration file and configure the application
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean) is
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Ctx : AWA.Services.Contexts.Service_Context;
Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager;
begin
Log.Info ("Reading application configuration file {0}", File);
Ctx.Set_Context (App'Unchecked_Access, null);
declare
package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context,
Override_Context);
pragma Warnings (Off, Config);
begin
Sec.Prepare_Config (Mapper);
-- Initialize the parser with the module configuration mappers (if any).
Initialize_Parser (App, Reader);
if Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.Mappers.Dump (Mapper, Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File, Mapper);
end;
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
-- ------------------------------
-- Get the configuration path for the application name.
-- The configuration path is search from:
-- o the current directory,
-- o the 'config' directory,
-- o the Dynamo installation directory in share/dynamo
-- ------------------------------
function Get_Config_Path (Name : in String) return String is
use Ada.Strings.Unbounded;
use Ada.Directories;
Command : constant String := Ada.Command_Line.Command_Name;
Path : constant String := Ada.Directories.Containing_Directory (Command);
Dir : constant String := Containing_Directory (Path);
Paths : Ada.Strings.Unbounded.Unbounded_String;
begin
Append (Paths, ".;");
Append (Paths, Util.Files.Compose (Dir, "config"));
Append (Paths, ";");
Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name));
return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths));
end Get_Config_Path;
end AWA.Applications.Configs;
|
Update to use the new parser/mapper interface
|
Update to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f6c2d58e8987c1ba664067329c610a3dd63593db
|
src/asf-filters-dump.adb
|
src/asf-filters-dump.adb
|
-----------------------------------------------------------------------
-- asf.filters.dump -- Filter to dump the request information
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Requests.Tools;
-- The <b>ASF.Filters.Dump</b> package provides a debugging filter which
-- can be activated in the request flow to dump the request content into
-- some log file before processing the request.
package body ASF.Filters.Dump is
use Ada.Strings.Unbounded;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Filters.Dump");
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
-- ------------------------------
procedure Do_Filter (F : in Dump_Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
Info : constant String := ASF.Requests.Tools.To_String (Req => Request,
Html => False,
Print_Headers => True,
Print_Attributes => True);
begin
Log.Info ("Request {0}", Info);
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
end ASF.Filters.Dump;
|
-----------------------------------------------------------------------
-- asf.filters.dump -- Filter to dump the request information
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Requests.Tools;
-- The <b>ASF.Filters.Dump</b> package provides a debugging filter which
-- can be activated in the request flow to dump the request content into
-- some log file before processing the request.
package body ASF.Filters.Dump is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Filters.Dump");
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
-- ------------------------------
procedure Do_Filter (F : in Dump_Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
Info : constant String := ASF.Requests.Tools.To_String (Req => Request,
Html => False,
Print_Headers => True,
Print_Attributes => True);
begin
Log.Info ("Request {0}", Info);
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
end ASF.Filters.Dump;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
55f8f499baa201ebea8330670867a5fff602e42f
|
src/gen-model-tables.ads
|
src/gen-model-tables.ads
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- 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 Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
Add a Is_Limited boolean property on each table (bean)
|
Add a Is_Limited boolean property on each table (bean)
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
078754b7c4e4df417c02140dc90a73ea7557df08
|
src/gen-model-tables.ads
|
src/gen-model-tables.ads
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the column is auditable (generate code to track changes).
Is_Auditable : Boolean := False;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Column_Definition;
Log : in out Util.Log.Logging'Class);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns true if the column is using a variable length (ex: a string).
function Is_Variable_Length (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Set the column type.
procedure Set_Type (Into : in out Column_Definition;
Name : in String);
-- Set the SQL length of the column.
procedure Set_Sql_Length (Into : in out Column_Definition;
Value : in String;
Log : in out Util.Log.Logging'Class);
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
-- The number of <<PK>> columns found.
Key_Count : Natural := 0;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
-- Whether the serialization operation have to be generated.
Is_Serializable : Boolean := False;
-- Whether the table contains auditable fields.
Is_Auditable : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Table_Definition;
Log : in out Util.Log.Logging'Class);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
use Ada.Strings.Unbounded;
type Table_Definition;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : Util.Beans.Objects.Object;
-- The column type name.
Type_Name : Unbounded_String;
-- The SQL type associated with the column.
Sql_Type : Unbounded_String;
-- The SQL name associated with the column.
Sql_Name : Unbounded_String;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the column is auditable (generate code to track changes).
Is_Auditable : Boolean := False;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : Util.Beans.Objects.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Column_Definition;
Log : in out Util.Log.Logging'Class);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns true if the column is using a variable length (ex: a string).
function Is_Variable_Length (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Set the column type.
procedure Set_Type (Into : in out Column_Definition;
Name : in String);
-- Set the SQL length of the column.
procedure Set_Sql_Length (Into : in out Column_Definition;
Value : in String;
Log : in out Util.Log.Logging'Class);
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : Util.Beans.Objects.Object;
Auditables : aliased Column_List.List_Definition;
Auditables_Bean : Util.Beans.Objects.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : Util.Beans.Objects.Object;
Parent : Table_Definition_Access;
Parent_Name : Unbounded_String;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Table_Name : Unbounded_String;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
-- The number of <<PK>> columns found.
Key_Count : Natural := 0;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
-- Whether the serialization operation have to be generated.
Is_Serializable : Boolean := False;
-- Whether the table contains auditable fields.
Is_Auditable : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Table_Definition;
Log : in out Util.Log.Logging'Class);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in Unbounded_String;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
Add Auditables and Auditables_Bean member in the Table_Definition
|
Add Auditables and Auditables_Bean member in the Table_Definition
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
ba1dd1ad40c074563311108511a05b5c0a3a855c
|
src/crash.adb
|
src/crash.adb
|
-- -*- Mode: Ada -*-
-- Filename : crash.adb
-- Description : Provides access to the multiboot information from GRUB
-- Legacy and GRUB 2.
-- Author : Luke A. Guest
-- Created On : Thur Nov 17 16:52:05 2016
-- Licence : See LICENCE in the root directory.
with Ada.Unchecked_Conversion;
with Interfaces.C;
with System.Address_To_Access_Conversions;
with System.Address_Operations; use System.Address_Operations;
with VGA_Console; use VGA_Console;
procedure Crash (Source_Location : System.Address; Line : Integer) is
package C renames Interfaces.C;
-- Get the length of the C NULL terminated string.
function Length (Source_Location : System.Address) return C.size_t is
use type C.size_t;
function Convert is new Ada.Unchecked_Conversion (Source => C.size_t,
Target => System.Address);
package To_Char is new System.Address_To_Access_Conversions (Object => C.char);
Count : C.size_t := 0;
Char : To_Char.Object_Pointer := To_Char.To_Pointer (AddA (Source_Location, Convert (Count)));
begin
while C.char'Pos (Char.all) /= 0 loop
Count := Count + 1;
Char := To_Char.To_Pointer (AddA (Source_Location, Convert (Count)));
end loop;
return Count;
end Length;
-- This is really ugly, just to convert an address pointing to a C NULL terminated string to an Ada String!
Source_Length : constant C.size_t := Length (Source_Location);
type Source_Chars is new C.char_array (0 .. Source_Length);
package To_Source is new System.Address_To_Access_Conversions (Object => Source_Chars);
Source_Str : constant String := C.To_Ada (C.char_array (To_Source.To_Pointer (Source_Location).all));
begin
Put (Str => "** Kernel crashed at: " & Source_Str & ":" & Integer'Image (Line) & " **",
X => 1,
Y => 10,
Foreground => White,
Background => Red);
-- TODO: Dump registers.
Hang : loop
null;
end loop Hang;
end Crash;
|
-- -*- Mode: Ada -*-
-- Filename : crash.adb
-- Description : Provides access to the multiboot information from GRUB
-- Legacy and GRUB 2.
-- Author : Luke A. Guest
-- Created On : Thur Nov 17 16:52:05 2016
-- Licence : See LICENCE in the root directory.
with Ada.Unchecked_Conversion;
with Interfaces.C;
with System.Address_To_Access_Conversions;
with System.Address_Operations; use System.Address_Operations;
with VGA_Console; use VGA_Console;
procedure Crash (Source_Location : System.Address; Line : Integer) is
package C renames Interfaces.C;
-- Get the length of the C NULL terminated string.
function Length (Source_Location : System.Address) return C.size_t is
use type C.size_t;
function Convert is new Ada.Unchecked_Conversion (Source => C.size_t,
Target => System.Address);
package To_Char is new System.Address_To_Access_Conversions (Object => C.char);
Count : C.size_t := 0;
Char : To_Char.Object_Pointer := To_Char.To_Pointer (AddA (Source_Location, Convert (Count)));
begin
while C.char'Pos (Char.all) /= 0 loop
Count := Count + 1;
Char := To_Char.To_Pointer (AddA (Source_Location, Convert (Count)));
end loop;
return Count;
end Length;
-- This is really ugly, just to convert an address pointing to a C NULL terminated string to an Ada String!
Source_Length : constant C.size_t := Length (Source_Location);
type Source_Chars is new C.char_array (0 .. Source_Length);
C_Str : Source_Chars with
Address => Source_Location;
pragma Import (Convention => Ada, Entity => C_Str);
Source_Str : constant String := C.To_Ada (C.char_array (C_Str));
begin
Put (Str => "** Kernel crashed at: " & Source_Str & ":" & Integer'Image (Line) & " **",
X => 1,
Y => 10,
Foreground => White,
Background => Red);
-- TODO: Dump registers.
Hang : loop
null;
end loop Hang;
end Crash;
|
Use memory overlay for the C string, much simpler.
|
Use memory overlay for the C string, much simpler.
|
Ada
|
cc0-1.0
|
Lucretia/bare_bones
|
251698a89e4978484e3910f5cd3ba90faa0febcd
|
mat/src/mat-targets-probes.ads
|
mat/src/mat-targets-probes.ads
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Events;
with MAT.Events.Targets;
with MAT.Events.Probes;
package MAT.Targets.Probes is
type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record
Target : Target_Type_Access;
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Events : MAT.Events.Targets.Target_Events_Access;
end record;
type Process_Probe_Type_Access is access all Process_Probe_Type'Class;
-- Create a new process after the begin event is received from the event stream.
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Extract the probe information from the message.
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type);
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type);
-- Register the reader to extract and analyze process events.
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access);
-- Initialize the target object to prepare for reading process events.
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
private
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message);
end MAT.Targets.Probes;
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Events;
with MAT.Events.Targets;
with MAT.Events.Probes;
package MAT.Targets.Probes is
type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record
Target : Target_Type_Access;
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Events : MAT.Events.Targets.Target_Events_Access;
end record;
type Process_Probe_Type_Access is access all Process_Probe_Type'Class;
-- Create a new process after the begin event is received from the event stream.
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Extract the probe information from the message.
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type);
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type);
-- Register the reader to extract and analyze process events.
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access);
-- Initialize the target object to prepare for reading process events.
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
private
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message);
-- Extract the information from the 'library' event.
procedure Probe_Library (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message);
end MAT.Targets.Probes;
|
Declare the Probe_Library procedure
|
Declare the Probe_Library procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5e56d8ace86944ddaefbe045b219779c61673769
|
src/orka/implementation/orka-transforms-simd_vectors.adb
|
src/orka/implementation/orka-transforms-simd_vectors.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Strings.Fixed;
package body Orka.Transforms.SIMD_Vectors is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type);
function Magnitude2 (Elements : Vector_Type) return Element_Type is
(Sum (Elements * Elements));
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is
begin
return (Factor, Factor, Factor, Factor) * Elements;
end "*";
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is
(Factor * Elements);
function Magnitude (Elements : Vector_Type) return Element_Type is
begin
return EF.Sqrt (Magnitude2 (Elements));
end Magnitude;
function Normalize (Elements : Vector_Type) return Vector_Type is
Length : constant Element_Type := Magnitude (Elements);
begin
return Divide_Or_Zero (Elements, (Length, Length, Length, Length));
end Normalize;
function Normalized (Elements : Vector_Type) return Boolean is
function Is_Equivalent (Expected, Result : Element_Type) return Boolean is
Epsilon : constant Element_Type := Element_Type'Model_Epsilon;
begin
return Result in Expected - Epsilon .. Expected + Epsilon;
end Is_Equivalent;
begin
return Is_Equivalent (1.0, Magnitude2 (Elements));
end Normalized;
function Distance (Left, Right : Vector_Type) return Element_Type is
(Magnitude (Left - Right));
function Projection (Elements, Direction : Vector_Type) return Vector_Type is
Unit_Direction : constant Vector_Type := Normalize (Direction);
begin
-- The dot product gives the magnitude of the projected vector:
-- |A_b| = |A| * cos(theta) = A . U_b
return Dot (Elements, Unit_Direction) * Unit_Direction;
end Projection;
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is
(Elements - Projection (Elements, Direction));
function Angle (Left, Right : Vector_Type) return Element_Type is
begin
return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right)), 360.0);
end Angle;
function Dot (Left, Right : Vector_Type) return Element_Type is
(Sum (Left * Right));
function Image (Elements : Vector_Type) return String is
use all type SIMD.Index_Homogeneous;
package SF renames Ada.Strings.Fixed;
use Ada.Strings;
begin
return "(" &
SF.Trim (Elements (X)'Image, Left) & ", " &
SF.Trim (Elements (Y)'Image, Left) & ", " &
SF.Trim (Elements (Z)'Image, Left) & ", " &
SF.Trim (Elements (W)'Image, Left) &
")";
end Image;
end Orka.Transforms.SIMD_Vectors;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Strings.Fixed;
package body Orka.Transforms.SIMD_Vectors is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type);
function Magnitude2 (Elements : Vector_Type) return Element_Type is
(Sum (Elements * Elements));
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is
begin
return (Factor, Factor, Factor, Factor) * Elements;
end "*";
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is
(Factor * Elements);
function Magnitude (Elements : Vector_Type) return Element_Type is
begin
return EF.Sqrt (Magnitude2 (Elements));
end Magnitude;
function Normalize (Elements : Vector_Type) return Vector_Type is
Length : constant Element_Type := Magnitude (Elements);
begin
return Divide_Or_Zero (Elements, (Length, Length, Length, Length));
end Normalize;
function Normalized (Elements : Vector_Type) return Boolean is
function Is_Equivalent (Expected, Result : Element_Type) return Boolean is
-- Because the square root is not computed, the bounds need
-- to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since
-- Epsilon < 1, we can simply take +/- 3 * Epsilon
Epsilon : constant Element_Type := 3.0 * Element_Type'Model_Epsilon;
begin
return Result in Expected - Epsilon .. Expected + Epsilon;
end Is_Equivalent;
begin
return Is_Equivalent (1.0, Magnitude2 (Elements));
end Normalized;
function Distance (Left, Right : Vector_Type) return Element_Type is
(Magnitude (Left - Right));
function Projection (Elements, Direction : Vector_Type) return Vector_Type is
Unit_Direction : constant Vector_Type := Normalize (Direction);
begin
-- The dot product gives the magnitude of the projected vector:
-- |A_b| = |A| * cos(theta) = A . U_b
return Dot (Elements, Unit_Direction) * Unit_Direction;
end Projection;
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is
(Elements - Projection (Elements, Direction));
function Angle (Left, Right : Vector_Type) return Element_Type is
begin
return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right)), 360.0);
end Angle;
function Dot (Left, Right : Vector_Type) return Element_Type is
(Sum (Left * Right));
function Image (Elements : Vector_Type) return String is
use all type SIMD.Index_Homogeneous;
package SF renames Ada.Strings.Fixed;
use Ada.Strings;
begin
return "(" &
SF.Trim (Elements (X)'Image, Left) & ", " &
SF.Trim (Elements (Y)'Image, Left) & ", " &
SF.Trim (Elements (Z)'Image, Left) & ", " &
SF.Trim (Elements (W)'Image, Left) &
")";
end Image;
end Orka.Transforms.SIMD_Vectors;
|
Increase epsilon in function Normalized
|
orka: Increase epsilon in function Normalized
Because the function does not compute the square root, the bounds need
to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since Epsilon < 1, we
can simply take +/- 3 * Epsilon.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.