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
|
---|---|---|---|---|---|---|---|---|---|
7955ccce7f31b50fda73e5e761a46a0515230fce
|
matp/src/mat-targets.ads
|
matp/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Frames.Targets;
with MAT.Readers;
with MAT.Readers.Streams;
with MAT.Readers.Streams.Sockets;
with MAT.Consoles;
with MAT.Expressions;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is received.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Print the events as they are received.
Print_Events : Boolean := False;
-- When true, start the mat server.
Server_Mode : Boolean := False;
-- The library search path.
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4606, others => <>);
end record;
type Target_Process_Type is new Ada.Finalization.Limited_Controlled
and MAT.Expressions.Resolver_Type with record
Pid : MAT.Types.Target_Process_Ref;
Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Events : MAT.Events.Targets.Target_Events_Access;
Frames : MAT.Frames.Targets.Target_Frames_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
-- Release the target process instance.
overriding
procedure Finalize (Target : in out Target_Process_Type);
-- Find the region that matches the given name.
overriding
function Find_Region (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Find the symbol in the symbol table and return the start and end address.
overriding
function Find_Symbol (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Get the start time for the tick reference.
overriding
function Get_Start_Time (Resolver : in Target_Process_Type)
return MAT.Types.Target_Tick_Ref;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
overriding
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class));
-- Add a search path for the library and symbol loader.
procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type;
Path : in String);
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
-- Release the storage used by the target object.
overriding
procedure Finalize (Target : in out Target_Type);
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014, 2015, 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.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Frames.Targets;
with MAT.Readers;
with MAT.Readers.Streams;
with MAT.Readers.Streams.Sockets;
with MAT.Consoles;
with MAT.Expressions;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is received.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Print the events as they are received.
Print_Events : Boolean := False;
-- When true, start the mat server.
Server_Mode : Boolean := False;
-- The library search path.
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4606, others => <>);
end record;
type Target_Process_Type is new Ada.Finalization.Limited_Controlled
and MAT.Expressions.Resolver_Type with record
Pid : MAT.Types.Target_Process_Ref;
Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Events : MAT.Events.Targets.Target_Events_Access;
Frames : MAT.Frames.Targets.Target_Frames_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
-- Release the target process instance.
overriding
procedure Finalize (Target : in out Target_Process_Type);
-- Find the region that matches the given name.
overriding
function Find_Region (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Find the symbol in the symbol table and return the start and end address.
overriding
function Find_Symbol (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Find the symbol region in the symbol table that contains the given address
-- and return the start and end address of that region.
overriding
function Find_Symbol (Resolver : in Target_Process_Type;
Addr : in MAT.Types.Target_Addr) return MAT.Memory.Region_Info;
-- Get the start time for the tick reference.
overriding
function Get_Start_Time (Resolver : in Target_Process_Type)
return MAT.Types.Target_Tick_Ref;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
overriding
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class));
-- Add a search path for the library and symbol loader.
procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type;
Path : in String);
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
-- Release the storage used by the target object.
overriding
procedure Finalize (Target : in out Target_Type);
end MAT.Targets;
|
Declare the Find_Symbol function
|
Declare the Find_Symbol function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
81b254a14fa2cd854ddc53b62d3d3c703b1fa35e
|
src/wiki.ads
|
src/wiki.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- 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.
-----------------------------------------------------------------------
-- == Wiki ==
-- The Wiki engine parses a Wiki text in several Wiki syntax such as <tt>MediaWiki</tt>,
-- <tt>Creole</tt>, <tt>Markdown</tt> and renders the result either in HTML, text or into
-- another Wiki format. The Wiki engine is used in two steps:
--
-- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance.
-- * The Wiki document is then rendered by a renderer to produce the final HTML, text.
--
-- [images/ada-wiki.png]
--
-- The Ada Wiki engine is organized in several packages:
--
-- * The Wiki stream packages define the interface, types and operations for the Wiki
-- engine to read the Wiki or HTML content and for the Wiki renderer to generate the
-- HTML or text outputs.
-- * The Wiki parser is responsible for parsing HTML or Wiki content according to a
-- selected Wiki syntax. It builds the final Wiki document through filters and plugins.
-- * The Wiki filters provides a simple filter framework that allows to plug specific
-- filters when a Wiki document is parsed and processed. Filters are used for the
-- table of content generation, for the HTML filtering, to collect words or links
-- and so on.
-- * The Wiki plugins defines the plugin interface that is used by the Wiki engine
-- to provide pluggable extensions in the Wiki. Plugins are used for the Wiki template
-- support, to hide some Wiki text content when it is rendered or to interact with
-- other systems.
-- * The Wiki documents and attributes are used for the representation of the Wiki
-- document after the Wiki content is parsed.
-- * The Wiki renderers are the last packages which are used for the rendering of the
-- Wiki document to produce the final HTML or text.
--
-- @include wiki-documents.ads
-- @include wiki-attributes.ads
-- @include wiki-parsers.ads
package Wiki is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Defines the possible text formats.
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag is
(
-- Section 4.1 The root element
ROOT_HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag) return String_Access;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
end Wiki;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- 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.
-----------------------------------------------------------------------
-- == Wiki ==
-- The Wiki engine parses a Wiki text in several Wiki syntax such as <tt>MediaWiki</tt>,
-- <tt>Creole</tt>, <tt>Markdown</tt> and renders the result either in HTML, text or into
-- another Wiki format. The Wiki engine is used in two steps:
--
-- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance.
-- * The Wiki document is then rendered by a renderer to produce the final HTML, text.
--
-- [images/ada-wiki.png]
--
-- The Ada Wiki engine is organized in several packages:
--
-- * The [Wiki_Streams Wiki stream] packages define the interface, types and operations for the Wiki
-- engine to read the Wiki or HTML content and for the Wiki renderer to generate the
-- HTML or text outputs.
-- * The Wiki parser is responsible for parsing HTML or Wiki content according to a
-- selected Wiki syntax. It builds the final Wiki document through filters and plugins.
-- * The [Wiki_Filters Wiki filters] provides a simple filter framework that allows to plug specific
-- filters when a Wiki document is parsed and processed. Filters are used for the
-- table of content generation, for the HTML filtering, to collect words or links
-- and so on.
-- * The [Wiki_Plugins Wiki plugins] defines the plugin interface that is used by the Wiki engine
-- to provide pluggable extensions in the Wiki. Plugins are used for the Wiki template
-- support, to hide some Wiki text content when it is rendered or to interact with
-- other systems.
-- * The Wiki documents and attributes are used for the representation of the Wiki
-- document after the Wiki content is parsed.
-- * The [Wiki_Render Wiki renderers] are the last packages which are used for the rendering of the
-- Wiki document to produce the final HTML or text.
--
-- @include wiki-documents.ads
-- @include wiki-attributes.ads
-- @include wiki-parsers.ads
package Wiki is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Defines the possible text formats.
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag is
(
-- Section 4.1 The root element
ROOT_HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag) return String_Access;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
end Wiki;
|
Add links to the documentation
|
Add links to the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8791c3cf6ac8a0cedf49b461192727271c3bd1d0
|
src/asf-components.ads
|
src/asf-components.ads
|
-----------------------------------------------------------------------
-- components -- Component tree
-- 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.
-----------------------------------------------------------------------
-- The <bASF.Components</b> describes the components that form the
-- tree view. Each component has attributes and children. Children
-- represent sub-components and attributes control the rendering and
-- behavior of the component.
--
-- The component tree is created from the <b>ASF.Views</b> tag nodes
-- for each request. Unlike tag nodes, the component tree is not shared.
with Ada.Strings.Unbounded;
with EL.Objects;
with EL.Expressions;
-- with EL.Contexts;
with ASF.Contexts.Faces;
-- limited with ASF.Contexts.Facelets;
limited with ASF.Views.Nodes;
limited with ASF.Converters;
package ASF.Components is
use Ada.Strings.Unbounded;
use ASF.Contexts.Faces;
type UIComponent_List is private;
-- ------------------------------
-- Attribute of a component
-- ------------------------------
type UIAttribute is private;
-- type UIComponent is new Ada.Finalization.Controlled with private;
type UIComponent is tagged limited private;
type UIComponent_Access is access all UIComponent'Class;
-- Get the parent component.
-- Returns null if the node is the root element.
function Get_Parent (UI : UIComponent) return UIComponent_Access;
-- Return a client-side identifier for this component, generating
-- one if necessary.
function Get_Client_Id (UI : UIComponent) return Unbounded_String;
-- Get the list of children.
function Get_Children (UI : UIComponent) return UIComponent_List;
-- Get the number of children.
function Get_Children_Count (UI : UIComponent) return Natural;
-- Get the first child component.
-- Returns null if the component has no children.
function Get_First_Child (UI : UIComponent) return UIComponent_Access;
-- Initialize the component when restoring the view.
-- The default initialization gets the client ID and allocates it if necessary.
procedure Initialize (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Append (UI : in UIComponent_Access;
Child : in UIComponent_Access;
Tag : access ASF.Views.Nodes.Tag_Node'Class);
-- Search for and return the {@link UIComponent} with an <code>id</code>
-- that matches the specified search expression (if any), according to
-- the algorithm described below.
function Find (UI : UIComponent;
Name : String) return UIComponent_Access;
-- Check whether the component and its children must be rendered.
function Is_Rendered (UI : UIComponent;
Context : Faces_Context'Class) return Boolean;
-- Set whether the component is rendered.
procedure Set_Rendered (UI : in out UIComponent;
Rendered : in Boolean);
function Get_Attribute (UI : UIComponent;
Context : Faces_Context'Class;
Name : String) return EL.Objects.Object;
-- Get the attribute tag
function Get_Attribute (UI : UIComponent;
Name : String) return access ASF.Views.Nodes.Tag_Attribute;
procedure Set_Attribute (UI : in out UIComponent;
Name : in String;
Value : in EL.Objects.Object);
procedure Set_Attribute (UI : in out UIComponent;
Def : access ASF.Views.Nodes.Tag_Attribute;
Value : in EL.Expressions.Expression);
-- Get the converter associated with the component
function Get_Converter (UI : in UIComponent;
Context : in Faces_Context'Class)
return access ASF.Converters.Converter'Class;
-- Convert the string into a value. If a converter is specified on the component,
-- use it to convert the value.
function Convert_Value (UI : in UIComponent;
Value : in String;
Context : in Faces_Context'Class) return EL.Objects.Object;
-- Get the value expression
function Get_Value_Expression (UI : in UIComponent;
Name : in String) return EL.Expressions.Value_Expression;
procedure Encode_Begin (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_Children (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_End (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_All (UI : in UIComponent'Class;
Context : in out Faces_Context'Class);
procedure Decode (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Decode_Children (UI : in UIComponent'Class;
Context : in out Faces_Context'Class);
procedure Process_Decodes (UI : in out UIComponent;
Context : in out Faces_Context'Class);
-- Perform the component tree processing required by the <b>Process Validations</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows:
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Validators</b> of all facets and children.
-- <ul>
procedure Process_Validators (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Process_Updates (UI : in out UIComponent;
Context : in out Faces_Context'Class);
type UIComponent_Array is array (Natural range <>) of UIComponent_Access;
type UIComponent_Array_Access is access UIComponent_Array;
-- type UIOutput is new UIComponent;
function Get_Context (UI : in UIComponent)
return ASF.Contexts.Faces.Faces_Context_Access;
-- Get the attribute value.
function Get_Value (Attr : UIAttribute;
UI : UIComponent'Class) return EL.Objects.Object;
-- function Create_UIComponent (Parent : UIComponent_Access;
-- Context : ASF.Contexts.Facelets.Facelet_Context'Class;
-- Tag : access ASF.Views.Nodes.Tag_Node'Class)
-- return UIComponent_Access;
-- Iterate over the children of the component and execute
-- the <b>Process</b> procedure.
generic
with procedure Process (Child : in UIComponent_Access);
procedure Iterate (UI : in UIComponent'Class);
-- Iterate over the attributes defined on the component and
-- execute the <b>Process</b> procedure.
generic
with procedure Process (Name : in String;
Attr : in UIAttribute);
procedure Iterate_Attributes (UI : in UIComponent'Class);
private
-- Delete the component tree recursively.
procedure Delete (UI : in out UIComponent_Access);
type UIAttribute_Access is access all UIAttribute;
type UIAttribute is record
Definition : access ASF.Views.Nodes.Tag_Attribute;
Name : Unbounded_String;
Value : EL.Objects.Object;
Expr : El.Expressions.Expression;
Next_Attr : UIAttribute_Access;
end record;
type UIComponent_List is record
Child : UIComponent_Access := null;
end record;
type UIComponent is tagged limited record
Id : Unbounded_String;
Tag : access ASF.Views.Nodes.Tag_Node'Class;
Parent : UIComponent_Access;
First_Child : UIComponent_Access;
Last_Child : UIComponent_Access;
Next : UIComponent_Access;
Attributes : UIAttribute_Access;
end record;
end ASF.Components;
|
-----------------------------------------------------------------------
-- components -- Component tree
-- 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.
-----------------------------------------------------------------------
-- The <bASF.Components</b> describes the components that form the
-- tree view. Each component has attributes and children. Children
-- represent sub-components and attributes control the rendering and
-- behavior of the component.
--
-- The component tree is created from the <b>ASF.Views</b> tag nodes
-- for each request. Unlike tag nodes, the component tree is not shared.
with Ada.Strings.Unbounded;
with EL.Objects;
with EL.Expressions;
-- with EL.Contexts;
with ASF.Contexts.Faces;
-- limited with ASF.Contexts.Facelets;
limited with ASF.Views.Nodes;
limited with ASF.Converters;
package ASF.Components is
use Ada.Strings.Unbounded;
use ASF.Contexts.Faces;
type UIComponent_List is private;
-- ------------------------------
-- Attribute of a component
-- ------------------------------
type UIAttribute is private;
-- type UIComponent is new Ada.Finalization.Controlled with private;
type UIComponent is tagged limited private;
type UIComponent_Access is access all UIComponent'Class;
-- Get the parent component.
-- Returns null if the node is the root element.
function Get_Parent (UI : UIComponent) return UIComponent_Access;
-- Return a client-side identifier for this component, generating
-- one if necessary.
function Get_Client_Id (UI : UIComponent) return Unbounded_String;
-- Get the list of children.
function Get_Children (UI : UIComponent) return UIComponent_List;
-- Get the number of children.
function Get_Children_Count (UI : UIComponent) return Natural;
-- Get the first child component.
-- Returns null if the component has no children.
function Get_First_Child (UI : UIComponent) return UIComponent_Access;
-- Initialize the component when restoring the view.
-- The default initialization gets the client ID and allocates it if necessary.
procedure Initialize (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Append (UI : in UIComponent_Access;
Child : in UIComponent_Access;
Tag : access ASF.Views.Nodes.Tag_Node'Class);
-- Search for and return the {@link UIComponent} with an <code>id</code>
-- that matches the specified search expression (if any), according to
-- the algorithm described below.
function Find (UI : UIComponent;
Name : String) return UIComponent_Access;
-- Check whether the component and its children must be rendered.
function Is_Rendered (UI : UIComponent;
Context : Faces_Context'Class) return Boolean;
-- Set whether the component is rendered.
procedure Set_Rendered (UI : in out UIComponent;
Rendered : in Boolean);
function Get_Attribute (UI : UIComponent;
Context : Faces_Context'Class;
Name : String) return EL.Objects.Object;
-- Get the attribute tag
function Get_Attribute (UI : UIComponent;
Name : String) return access ASF.Views.Nodes.Tag_Attribute;
procedure Set_Attribute (UI : in out UIComponent;
Name : in String;
Value : in EL.Objects.Object);
procedure Set_Attribute (UI : in out UIComponent;
Def : access ASF.Views.Nodes.Tag_Attribute;
Value : in EL.Expressions.Expression);
-- Get the converter associated with the component
function Get_Converter (UI : in UIComponent;
Context : in Faces_Context'Class)
return access ASF.Converters.Converter'Class;
-- Convert the string into a value. If a converter is specified on the component,
-- use it to convert the value.
function Convert_Value (UI : in UIComponent;
Value : in String;
Context : in Faces_Context'Class) return EL.Objects.Object;
-- Get the value expression
function Get_Value_Expression (UI : in UIComponent;
Name : in String) return EL.Expressions.Value_Expression;
procedure Encode_Begin (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_Children (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_End (UI : in UIComponent;
Context : in out Faces_Context'Class);
procedure Encode_All (UI : in UIComponent'Class;
Context : in out Faces_Context'Class);
procedure Decode (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Decode_Children (UI : in UIComponent'Class;
Context : in out Faces_Context'Class);
procedure Process_Decodes (UI : in out UIComponent;
Context : in out Faces_Context'Class);
-- Perform the component tree processing required by the <b>Process Validations</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows:
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Validators</b> of all facets and children.
-- <ul>
procedure Process_Validators (UI : in out UIComponent;
Context : in out Faces_Context'Class);
procedure Process_Updates (UI : in out UIComponent;
Context : in out Faces_Context'Class);
type UIComponent_Array is array (Natural range <>) of UIComponent_Access;
type UIComponent_Array_Access is access UIComponent_Array;
-- type UIOutput is new UIComponent;
function Get_Context (UI : in UIComponent)
return ASF.Contexts.Faces.Faces_Context_Access;
-- Get the attribute value.
function Get_Value (Attr : UIAttribute;
UI : UIComponent'Class) return EL.Objects.Object;
-- function Create_UIComponent (Parent : UIComponent_Access;
-- Context : ASF.Contexts.Facelets.Facelet_Context'Class;
-- Tag : access ASF.Views.Nodes.Tag_Node'Class)
-- return UIComponent_Access;
-- Iterate over the children of the component and execute
-- the <b>Process</b> procedure.
generic
with procedure Process (Child : in UIComponent_Access);
procedure Iterate (UI : in UIComponent'Class);
-- Iterate over the attributes defined on the component and
-- execute the <b>Process</b> procedure.
generic
with procedure Process (Name : in String;
Attr : in UIAttribute);
procedure Iterate_Attributes (UI : in UIComponent'Class);
-- ------------------------------
-- Value Holder
-- ------------------------------
type Value_Holder is limited interface;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
function Get_Local_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
function Get_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Set the value of the component.
procedure Set_Value (Holder : in out Value_Holder;
Value : in EL.Objects.Object) is abstract;
-- Get the converter that is registered on the component.
function Get_Converter (Holder : in Value_Holder)
return access ASF.Converters.Converter'Class is abstract;
-- Set the converter to be used on the component.
procedure Set_Converter (Holder : in out Value_Holder;
Converter : access ASF.Converters.Converter'Class) is abstract;
private
-- Delete the component tree recursively.
procedure Delete (UI : in out UIComponent_Access);
type UIAttribute_Access is access all UIAttribute;
type UIAttribute is record
Definition : access ASF.Views.Nodes.Tag_Attribute;
Name : Unbounded_String;
Value : EL.Objects.Object;
Expr : El.Expressions.Expression;
Next_Attr : UIAttribute_Access;
end record;
type UIComponent_List is record
Child : UIComponent_Access := null;
end record;
type UIComponent is tagged limited record
Id : Unbounded_String;
Tag : access ASF.Views.Nodes.Tag_Node'Class;
Parent : UIComponent_Access;
First_Child : UIComponent_Access;
Last_Child : UIComponent_Access;
Next : UIComponent_Access;
Attributes : UIAttribute_Access;
end record;
end ASF.Components;
|
Define the Value_Holder interface
|
Define the Value_Holder interface
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dd17dd44f4ae56e4a3758cd32eefed44547d8d93
|
src/imago-ilut.ads
|
src/imago-ilut.ads
|
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: ISC --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
with Imago.IL;
use Imago;
with Lumen.GL;
use Lumen;
package Imago.ILUT is
--------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
--------------------------------------------------------------------------
ILUT_VERSION_1_7_8 : constant IL.Enum := 1;
ILUT_VERSION : constant IL.Enum := 178;
-- Attribute Bits.
ILUT_OPENGL_BIT : constant IL.Enum := 16#00000001#;
ILUT_D3D_BIT : constant IL.Enum := 16#00000002#;
ILUT_ALL_ATTRIB_BITS : constant IL.Enum := 16#000FFFFF#;
-- Error Types.
ILUT_INVALID_ENUM : constant IL.Enum := 16#0501#;
ILUT_OUT_OF_MEMORY : constant IL.Enum := 16#0502#;
ILUT_INVALID_VALUE : constant IL.Enum := 16#0505#;
ILUT_ILLEGAL_OPERATION : constant IL.Enum := 16#0506#;
ILUT_INVALID_PARAM : constant IL.Enum := 16#0509#;
ILUT_COULD_NOT_OPEN_FILE : constant IL.Enum := 16#050A#;
ILUT_STACK_OVERFLOW : constant IL.Enum := 16#050E#;
ILUT_STACK_UNDERFLOW : constant IL.Enum := 16#050F#;
ILUT_BAD_DIMENSIONS : constant IL.Enum := 16#0511#;
ILUT_NOT_SUPPORTED : constant IL.Enum := 16#0550#;
-- State Definitions.
ILUT_PALETTE_MODE : constant IL.Enum := 16#0600#;
ILUT_OPENGL_CONV : constant IL.Enum := 16#0610#;
ILUT_D3D_MIPLEVELS : constant IL.Enum := 16#0620#;
ILUT_MAXTEX_WIDTH : constant IL.Enum := 16#0630#;
ILUT_MAXTEX_HEIGHT : constant IL.Enum := 16#0631#;
ILUT_MAXTEX_DEPTH : constant IL.Enum := 16#0632#;
ILUT_GL_USE_S3TC : constant IL.Enum := 16#0634#;
ILUT_D3D_USE_DXTC : constant IL.Enum := 16#0634#;
ILUT_GL_GEN_S3TC : constant IL.Enum := 16#0635#;
ILUT_D3D_GEN_DXTC : constant IL.Enum := 16#0635#;
ILUT_S3TC_FORMAT : constant IL.Enum := 16#0705#;
ILUT_DXTC_FORMAT : constant IL.Enum := 16#0705#;
ILUT_D3D_POOL : constant IL.Enum := 16#0706#;
ILUT_D3D_ALPHA_KEY_COLOR : constant IL.Enum := 16#0707#;
ILUT_D3D_ALPHA_KEY_COLOUR : constant IL.Enum := 16#0707#;
ILUT_FORCE_INTEGER_FORMAT : constant IL.Enum := 16#0636#;
-- This new state does automatic texture target detection
-- if enabled. Currently, only cubemap detection is supported.
-- if the current image is no cubemap, the 2d texture is chosen.
ILUT_GL_AUTODETECT_TEXTURE_TARGET : constant IL.Enum := 16#0807#;
-- Values.
ILUT_VERSION_NUM : constant IL.Enum := IL.IL_VERSION_NUM;
ILUT_VENDOR : constant IL.Enum := IL.IL_VENDOR;
-- The different rendering api's.
-- NOTE: Imago has support only for OpenGL functions.
-- Addition of support for other bindings is not planned.
ILUT_OPENGL : constant IL.Enum := 0;
ILUT_ALLEGRO : constant IL.Enum := 1;
ILUT_WIN32 : constant IL.Enum := 2;
ILUT_DIRECT3D8 : constant IL.Enum := 3;
ILUT_DIRECT3D9 : constant IL.Enum := 4;
ILUT_X11 : constant IL.Enum := 5;
ILUT_DIRECT3D10 : constant IL.Enum := 6;
--------------------------------------------------------------------------
---------------------------
-- S U B P R O G R A M S --
---------------------------
--------------------------------------------------------------------------
-- ImageLib Utility Toolkit Functions.
function Disable (Mode: in IL.Enum) return IL.Bool;
function Enable (Mode: in IL.Enum) return IL.Bool;
function Get_Boolean (Mode: in IL.Enum) return IL.Bool;
procedure Get_Boolean (Mode: in IL.Enum; Param: in IL.Pointer);
pragma Inline (Get_Boolean);
function Get_Integer (Mode: in IL.Enum) return IL.Int;
procedure Get_Integer (Mode: in IL.Enum; Param: in IL.Pointer);
pragma Inline (Get_Integer);
function Get_String (String_Name: in IL.Enum) return String;
pragma Inline (Get_String);
procedure Init;
function Is_Disabled (Mode: in IL.Enum) return IL.Bool;
function Is_Enabled (Mode: in IL.Enum) return IL.Bool;
procedure Pop_Attrib;
procedure Push_Attrib (Bits: in IL.UInt);
procedure Set_Integer (Mode: in IL.Enum; Param: in IL.Int);
function Renderer (Renderer: in IL.Enum) return IL.Bool;
-- ImageLib Utility Toolkit's OpenGL Functions.
function GL_Bind_Tex_Image return GL.UInt;
function GL_Bind_Mipmaps return GL.UInt;
function GL_Build_Mipmaps return IL.Bool;
function GL_Load_Image (File_Name: in String) return GL.UInt;
pragma Inline (GL_Load_Image);
function GL_Screen return IL.Bool;
function GL_Screenie return IL.Bool;
function GL_Save_Image
( File_Name: in String; Tex_ID: in GL.UInt
) return IL.Bool;
pragma Inline (GL_Save_Image);
function GL_Sub_Tex
( Tex_ID: in GL.UInt; XOff: in IL.UInt; YOff: in IL.UInt
) return IL.Bool;
function GL_Sub_Tex
( Tex_ID: in GL.UInt; XOff: in IL.UInt;
YOff: in IL.UInt; ZOff: in IL.UInt
) return IL.Bool;
pragma Inline (GL_Sub_Tex);
function GL_Set_Tex_2D (Tex_ID: in GL.UInt) return IL.Bool;
pragma Import (StdCall, GL_Set_Tex_2D, "ilutGLSetTex2D");
function GL_Set_Tex_3D (Tex_ID: in GL.UInt) return IL.Bool;
pragma Import (StdCall, GL_Set_Tex_3D, "ilutGLSetTex3D");
function GL_Tex_Image (Level: in GL.UInt) return IL.Bool;
pragma Import (StdCall, GL_Tex_Image, "ilutGLTexImage");
---------------------------------------------------------------------------
private
--------------------------------------------------------------------------
-------------------
-- I M P O R T S --
-------------------
--------------------------------------------------------------------------
pragma Import (StdCall, Disable, "ilutDisable");
pragma Import (StdCall, Enable, "ilutEnable");
pragma Import (StdCall, Init, "ilutInit");
pragma Import (StdCall, Is_Disabled, "ilutIsDisabled");
pragma Import (StdCall, Is_Enabled, "ilutIsEnabled");
pragma Import (StdCall, Pop_Attrib, "ilutPopAttrib");
pragma Import (StdCall, Push_Attrib, "ilutPushAttrib");
pragma Import (StdCall, Set_Integer, "ilutSetInteger");
pragma Import (StdCall, Renderer, "ilutRenderer");
-- OpenGL dependent subprograms
pragma Import (StdCall, GL_Bind_Tex_Image, "ilutGLBindTexImage");
pragma Import (StdCall, GL_Bind_Mipmaps, "ilutGLBindMipmaps");
pragma Import (StdCall, GL_Build_Mipmaps, "ilutGLBuildMipmaps");
pragma Import (StdCall, GL_Screen, "ilutGLScreen");
pragma Import (StdCall, GL_Screenie, "ilutGLScreenie");
--------------------------------------------------------------------------
end Imago.ILUT;
|
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: ISC --
-- --
-- Copyright © 2015 - 2016 darkestkhan --
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
with Imago.IL;
use Imago;
with Lumen.GL;
use Lumen;
package Imago.ILUT is
--------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
--------------------------------------------------------------------------
ILUT_VERSION_1_7_8 : constant IL.Enum := 1;
ILUT_VERSION : constant IL.Enum := 178;
-- Attribute Bits.
ILUT_OPENGL_BIT : constant IL.Enum := 16#00000001#;
ILUT_D3D_BIT : constant IL.Enum := 16#00000002#;
ILUT_ALL_ATTRIB_BITS : constant IL.Enum := 16#000FFFFF#;
-- Error Types.
ILUT_INVALID_ENUM : constant IL.Enum := 16#0501#;
ILUT_OUT_OF_MEMORY : constant IL.Enum := 16#0502#;
ILUT_INVALID_VALUE : constant IL.Enum := 16#0505#;
ILUT_ILLEGAL_OPERATION : constant IL.Enum := 16#0506#;
ILUT_INVALID_PARAM : constant IL.Enum := 16#0509#;
ILUT_COULD_NOT_OPEN_FILE : constant IL.Enum := 16#050A#;
ILUT_STACK_OVERFLOW : constant IL.Enum := 16#050E#;
ILUT_STACK_UNDERFLOW : constant IL.Enum := 16#050F#;
ILUT_BAD_DIMENSIONS : constant IL.Enum := 16#0511#;
ILUT_NOT_SUPPORTED : constant IL.Enum := 16#0550#;
-- State Definitions.
ILUT_PALETTE_MODE : constant IL.Enum := 16#0600#;
ILUT_OPENGL_CONV : constant IL.Enum := 16#0610#;
ILUT_D3D_MIPLEVELS : constant IL.Enum := 16#0620#;
ILUT_MAXTEX_WIDTH : constant IL.Enum := 16#0630#;
ILUT_MAXTEX_HEIGHT : constant IL.Enum := 16#0631#;
ILUT_MAXTEX_DEPTH : constant IL.Enum := 16#0632#;
ILUT_GL_USE_S3TC : constant IL.Enum := 16#0634#;
ILUT_D3D_USE_DXTC : constant IL.Enum := 16#0634#;
ILUT_GL_GEN_S3TC : constant IL.Enum := 16#0635#;
ILUT_D3D_GEN_DXTC : constant IL.Enum := 16#0635#;
ILUT_S3TC_FORMAT : constant IL.Enum := 16#0705#;
ILUT_DXTC_FORMAT : constant IL.Enum := 16#0705#;
ILUT_D3D_POOL : constant IL.Enum := 16#0706#;
ILUT_D3D_ALPHA_KEY_COLOR : constant IL.Enum := 16#0707#;
ILUT_D3D_ALPHA_KEY_COLOUR : constant IL.Enum := 16#0707#;
ILUT_FORCE_INTEGER_FORMAT : constant IL.Enum := 16#0636#;
-- This new state does automatic texture target detection
-- if enabled. Currently, only cubemap detection is supported.
-- if the current image is no cubemap, the 2d texture is chosen.
ILUT_GL_AUTODETECT_TEXTURE_TARGET : constant IL.Enum := 16#0807#;
-- Values.
ILUT_VERSION_NUM : constant IL.Enum := IL.IL_VERSION_NUM;
ILUT_VENDOR : constant IL.Enum := IL.IL_VENDOR;
-- The different rendering api's.
-- NOTE: Imago has support only for OpenGL functions.
-- Addition of support for other bindings is not planned.
ILUT_OPENGL : constant IL.Enum := 0;
ILUT_ALLEGRO : constant IL.Enum := 1;
ILUT_WIN32 : constant IL.Enum := 2;
ILUT_DIRECT3D8 : constant IL.Enum := 3;
ILUT_DIRECT3D9 : constant IL.Enum := 4;
ILUT_X11 : constant IL.Enum := 5;
ILUT_DIRECT3D10 : constant IL.Enum := 6;
--------------------------------------------------------------------------
---------------------------
-- S U B P R O G R A M S --
---------------------------
--------------------------------------------------------------------------
-- ImageLib Utility Toolkit Functions.
function Disable (Mode: in IL.Enum) return IL.Bool;
function Enable (Mode: in IL.Enum) return IL.Bool;
function Get_Boolean (Mode: in IL.Enum) return IL.Bool;
procedure Get_Boolean (Mode: in IL.Enum; Param: in IL.Pointer);
pragma Inline (Get_Boolean);
function Get_Integer (Mode: in IL.Enum) return IL.Int;
procedure Get_Integer (Mode: in IL.Enum; Param: in IL.Pointer);
pragma Inline (Get_Integer);
function Get_String (String_Name: in IL.Enum) return String;
pragma Inline (Get_String);
procedure Init;
function Is_Disabled (Mode: in IL.Enum) return IL.Bool;
function Is_Enabled (Mode: in IL.Enum) return IL.Bool;
procedure Pop_Attrib;
procedure Push_Attrib (Bits: in IL.UInt);
procedure Set_Integer (Mode: in IL.Enum; Param: in IL.Int);
function Renderer (Renderer: in IL.Enum) return IL.Bool;
-- ImageLib Utility Toolkit's OpenGL Functions.
function GL_Bind_Tex_Image return GL.UInt;
function GL_Bind_Mipmaps return GL.UInt;
function GL_Build_Mipmaps return IL.Bool;
function GL_Load_Image (File_Name: in String) return GL.UInt;
pragma Inline (GL_Load_Image);
function GL_Screen return IL.Bool;
function GL_Screenie return IL.Bool;
function GL_Save_Image
( File_Name: in String; Tex_ID: in GL.UInt
) return IL.Bool;
pragma Inline (GL_Save_Image);
function GL_Sub_Tex
( Tex_ID: in GL.UInt; XOff: in IL.UInt; YOff: in IL.UInt
) return IL.Bool;
function GL_Sub_Tex
( Tex_ID: in GL.UInt; XOff: in IL.UInt;
YOff: in IL.UInt; ZOff: in IL.UInt
) return IL.Bool;
pragma Inline (GL_Sub_Tex);
function GL_Set_Tex_2D (Tex_ID: in GL.UInt) return IL.Bool;
function GL_Set_Tex_3D (Tex_ID: in GL.UInt) return IL.Bool;
function GL_Tex_Image (Level: in GL.UInt) return IL.Bool;
---------------------------------------------------------------------------
private
--------------------------------------------------------------------------
-------------------
-- I M P O R T S --
-------------------
--------------------------------------------------------------------------
pragma Import (StdCall, Disable, "ilutDisable");
pragma Import (StdCall, Enable, "ilutEnable");
pragma Import (StdCall, Init, "ilutInit");
pragma Import (StdCall, Is_Disabled, "ilutIsDisabled");
pragma Import (StdCall, Is_Enabled, "ilutIsEnabled");
pragma Import (StdCall, Pop_Attrib, "ilutPopAttrib");
pragma Import (StdCall, Push_Attrib, "ilutPushAttrib");
pragma Import (StdCall, Set_Integer, "ilutSetInteger");
pragma Import (StdCall, Renderer, "ilutRenderer");
-- OpenGL dependent subprograms
pragma Import (StdCall, GL_Bind_Tex_Image, "ilutGLBindTexImage");
pragma Import (StdCall, GL_Bind_Mipmaps, "ilutGLBindMipmaps");
pragma Import (StdCall, GL_Build_Mipmaps, "ilutGLBuildMipmaps");
pragma Import (StdCall, GL_Screen, "ilutGLScreen");
pragma Import (StdCall, GL_Screenie, "ilutGLScreenie");
pragma Import (StdCall, GL_Set_Tex_2D, "ilutGLSetTex2D");
pragma Import (StdCall, GL_Set_Tex_3D, "ilutGLSetTex3D");
pragma Import (StdCall, GL_Tex_Image, "ilutGLTexImage");
--------------------------------------------------------------------------
end Imago.ILUT;
|
Move Import pragmas to private part.
|
ILUT: Move Import pragmas to private part.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/imago
|
72a0afc5358b7b2f454c46a06843875ac42aad96
|
src/natools-web-acl-sx_backends.adb
|
src/natools-web-acl-sx_backends.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2017-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
package body Natools.Web.ACL.Sx_Backends is
type Hashed_Token_List_Array is array (Hash_Id range <>)
of Containers.Unsafe_Atom_Lists.List;
type Hashed_Token_Map_Array is array (Hash_Id range <>)
of Token_Maps.Unsafe_Maps.Map;
type User_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record
Tokens, Groups : Containers.Unsafe_Atom_Lists.List;
Hashed : Hashed_Token_List_Array (Hash_Id_First .. Hash_Id_Last);
end record;
type Backend_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record
Map : Token_Maps.Unsafe_Maps.Map;
Hashed : Hashed_Token_Map_Array (Hash_Id_First .. Hash_Id_Last);
end record;
Cookie_Name : constant String := "User-Token";
Hash_Mark : constant Character := '$';
procedure Process_User
(Builder : in out Backend_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class);
procedure Process_User_Element
(Builder : in out User_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class);
procedure Read_DB is new S_Expressions.Interpreter_Loop
(Backend_Builder, Meaningless_Type, Process_User);
procedure Read_User is new S_Expressions.Interpreter_Loop
(User_Builder, Meaningless_Type, Process_User_Element);
--------------------------
-- Constructor Elements --
--------------------------
procedure Process_User
(Builder : in out Backend_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
User : User_Builder (Builder.Hash_Id_First, Builder.Hash_Id_Last);
Identity : Containers.Identity;
begin
Read_User (Arguments, User, Meaningless_Value);
Identity :=
(User => S_Expressions.Atom_Ref_Constructors.Create (Name),
Groups => Containers.Create (User.Groups));
for Token of User.Tokens loop
Builder.Map.Include (Token, Identity);
end loop;
for Id in User.Hashed'Range loop
for Hashed_Token of User.Hashed (Id) loop
Builder.Hashed (Id).Include (Hashed_Token, Identity);
end loop;
end loop;
end Process_User;
procedure Process_User_Element
(Builder : in out User_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
S_Name : constant String := S_Expressions.To_String (Name);
begin
if S_Name = "tokens" or else S_Name = "token" then
Containers.Append_Atoms (Builder.Tokens, Arguments);
elsif S_Name = "groups" or else S_Name = "group" then
Containers.Append_Atoms (Builder.Groups, Arguments);
elsif (S_Name'Length = 8
or else (S_Name'Length = 9 and then S_Name (S_Name'Last) = 's'))
and then S_Name (S_Name'First) = Hash_Mark
and then S_Name (S_Name'First + 2 .. S_Name'First + 7)
= Hash_Mark & "token"
and then not Hash_Function_DB.Is_Empty
then
declare
Id : constant Character := S_Name (S_Name'First + 1);
Acc : constant Hash_Function_Array_Refs.Accessor
:= Hash_Function_DB.Query;
begin
if Id in Acc.Data.all'Range and then Acc.Data (Id) /= null then
Containers.Append_Atoms (Builder.Hashed (Id), Arguments);
else
Log (Severities.Error, "Unknown hash function id"
& Character'Image (Id));
end if;
end;
else
Log (Severities.Error, "Unknown user element """ & S_Name & '"');
end if;
end Process_User_Element;
----------------------
-- Public Interface --
----------------------
overriding procedure Authenticate
(Self : in Backend;
Exchange : in out Exchanges.Exchange)
is
Cookie : constant String := Exchange.Cookie (Cookie_Name);
Identity : Containers.Identity;
begin
if Cookie'Length > 3
and then Cookie (Cookie'First) = Hash_Mark
and then Cookie (Cookie'First + 2) = Hash_Mark
and then not Self.Hashed.Is_Empty
and then Cookie (Cookie'First + 1) in Self.Hashed.Query.Data.all'Range
then
declare
Token : constant S_Expressions.Atom
:= S_Expressions.To_Atom
(Cookie (Cookie'First + 3 .. Cookie'Last));
Hash : constant S_Expressions.Atom
:= Hash_Function_DB.Query.Data (Cookie (Cookie'First + 1)).all
(Token);
Cursor : constant Token_Maps.Cursor
:= Self.Hashed.Query.Data (Cookie (Cookie'First + 1)).Find
(Hash);
begin
if Token_Maps.Has_Element (Cursor) then
Identity := Token_Maps.Element (Cursor);
end if;
end;
else
declare
Cursor : constant Token_Maps.Cursor
:= Self.Map.Find (S_Expressions.To_Atom (Cookie));
begin
if Token_Maps.Has_Element (Cursor) then
Identity := Token_Maps.Element (Cursor);
end if;
end;
end if;
Exchange.Set_Identity (Identity);
end Authenticate;
function Create
(Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return ACL.Backend'Class
is
Hash_Id_First : constant Hash_Id
:= (if Hash_Function_DB.Is_Empty
then Hash_Id'Last
else Hash_Function_DB.Query.Data.all'First);
Hash_Id_Last : constant Hash_Id
:= (if Hash_Function_DB.Is_Empty
then Hash_Id'First
else Hash_Function_DB.Query.Data.all'Last);
Builder : Backend_Builder (Hash_Id_First, Hash_Id_Last);
begin
case Arguments.Current_Event is
when S_Expressions.Events.Open_List =>
Read_DB (Arguments, Builder, Meaningless_Value);
when S_Expressions.Events.Add_Atom =>
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Arguments.Current_Atom));
begin
Read_DB (Reader, Builder, Meaningless_Value);
end;
when others =>
Log (Severities.Error, "Unable to create ACL from S-expression"
& " starting with " & Arguments.Current_Event'Img);
end case;
return Result : Backend
:= (Map => Token_Maps.Create (Builder.Map),
Hashed => <>)
do
declare
Min : Hash_Id := Hash_Id'Last;
Max : Hash_Id := Hash_Id'First;
begin
for Id in Builder.Hashed'Range loop
if not Builder.Hashed (Id).Is_Empty then
-- Hash_Id'Min seems broken, using a basic `if` instead
if Id < Min then
Min := Id;
end if;
if Id > Max then
Max := Id;
end if;
end if;
end loop;
if Min <= Max then
declare
Data : constant Hashed_Token_Array_Refs.Data_Access
:= new Hashed_Token_Array (Min .. Max);
begin
Result.Hashed := Hashed_Token_Array_Refs.Create (Data);
for Id in Min .. Max loop
if not Builder.Hashed (Id).Is_Empty then
Data (Id) := Token_Maps.Create (Builder.Hashed (Id));
end if;
end loop;
end;
end if;
end;
end return;
end Create;
procedure Register
(Id : in Character;
Fn : in Hash_Function) is
begin
if Fn = null then
null;
elsif Hash_Function_DB.Is_Empty then
Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn));
elsif Id in Hash_Function_DB.Query.Data.all'Range then
Hash_Function_DB.Update.Data.all (Id) := Fn;
else
declare
New_First : constant Hash_Id
:= Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First);
New_Last : constant Hash_Id
:= Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last);
New_Data : constant Hash_Function_Array_Refs.Data_Access
:= new Hash_Function_Array'(New_First .. New_Last => null);
begin
Log (Severities.Info,
"Adding " & Id'Img & " to "
& Hash_Function_DB.Query.Data.all'First'Img & " .. "
& Hash_Function_DB.Query.Data.all'Last'Img & " -> "
& New_First'Img & " .. " & New_Last'Img);
New_Data (Hash_Function_DB.Query.Data.all'First
.. Hash_Function_DB.Query.Data.all'Last)
:= Hash_Function_DB.Query.Data.all;
Hash_Function_DB.Replace (New_Data);
end;
end if;
end Register;
end Natools.Web.ACL.Sx_Backends;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
package body Natools.Web.ACL.Sx_Backends is
type Hashed_Token_List_Array is array (Hash_Id range <>)
of Containers.Unsafe_Atom_Lists.List;
type Hashed_Token_Map_Array is array (Hash_Id range <>)
of Token_Maps.Unsafe_Maps.Map;
type User_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record
Tokens, Groups : Containers.Unsafe_Atom_Lists.List;
Hashed : Hashed_Token_List_Array (Hash_Id_First .. Hash_Id_Last);
end record;
type Backend_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record
Map : Token_Maps.Unsafe_Maps.Map;
Hashed : Hashed_Token_Map_Array (Hash_Id_First .. Hash_Id_Last);
end record;
Cookie_Name : constant String := "User-Token";
Hash_Mark : constant Character := '$';
procedure Process_User
(Builder : in out Backend_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class);
procedure Process_User_Element
(Builder : in out User_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class);
procedure Read_DB is new S_Expressions.Interpreter_Loop
(Backend_Builder, Meaningless_Type, Process_User);
procedure Read_User is new S_Expressions.Interpreter_Loop
(User_Builder, Meaningless_Type, Process_User_Element);
--------------------------
-- Constructor Elements --
--------------------------
procedure Process_User
(Builder : in out Backend_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
User : User_Builder (Builder.Hash_Id_First, Builder.Hash_Id_Last);
Identity : Containers.Identity;
begin
Read_User (Arguments, User, Meaningless_Value);
Identity :=
(User => S_Expressions.Atom_Ref_Constructors.Create (Name),
Groups => Containers.Create (User.Groups));
for Token of User.Tokens loop
Builder.Map.Include (Token, Identity);
end loop;
for Id in User.Hashed'Range loop
for Hashed_Token of User.Hashed (Id) loop
Builder.Hashed (Id).Include (Hashed_Token, Identity);
end loop;
end loop;
end Process_User;
procedure Process_User_Element
(Builder : in out User_Builder;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
S_Name : constant String := S_Expressions.To_String (Name);
begin
if S_Name = "tokens" or else S_Name = "token" then
Containers.Append_Atoms (Builder.Tokens, Arguments);
elsif S_Name = "groups" or else S_Name = "group" then
Containers.Append_Atoms (Builder.Groups, Arguments);
elsif (S_Name'Length = 8
or else (S_Name'Length = 9 and then S_Name (S_Name'Last) = 's'))
and then S_Name (S_Name'First) = Hash_Mark
and then S_Name (S_Name'First + 2 .. S_Name'First + 7)
= Hash_Mark & "token"
and then not Hash_Function_DB.Is_Empty
then
declare
Id : constant Character := S_Name (S_Name'First + 1);
Acc : constant Hash_Function_Array_Refs.Accessor
:= Hash_Function_DB.Query;
begin
if Id in Acc.Data.all'Range and then Acc.Data (Id) /= null then
Containers.Append_Atoms (Builder.Hashed (Id), Arguments);
else
Log (Severities.Error, "Unknown hash function id"
& Character'Image (Id));
end if;
end;
else
Log (Severities.Error, "Unknown user element """ & S_Name & '"');
end if;
end Process_User_Element;
----------------------
-- Public Interface --
----------------------
overriding procedure Authenticate
(Self : in Backend;
Exchange : in out Exchanges.Exchange)
is
Cookie : constant String := Exchange.Cookie (Cookie_Name);
Identity : Containers.Identity;
begin
if Cookie'Length > 3
and then Cookie (Cookie'First) = Hash_Mark
and then Cookie (Cookie'First + 2) = Hash_Mark
and then not Self.Hashed.Is_Empty
and then Cookie (Cookie'First + 1) in Self.Hashed.Query.Data.all'Range
then
declare
Token : constant S_Expressions.Atom
:= S_Expressions.To_Atom
(Cookie (Cookie'First + 3 .. Cookie'Last));
Hash : constant S_Expressions.Atom
:= Hash_Function_DB.Query.Data (Cookie (Cookie'First + 1)).all
(Token);
Cursor : constant Token_Maps.Cursor
:= Self.Hashed.Query.Data (Cookie (Cookie'First + 1)).Find
(Hash);
begin
if Token_Maps.Has_Element (Cursor) then
Identity := Token_Maps.Element (Cursor);
end if;
end;
else
declare
Cursor : constant Token_Maps.Cursor
:= Self.Map.Find (S_Expressions.To_Atom (Cookie));
begin
if Token_Maps.Has_Element (Cursor) then
Identity := Token_Maps.Element (Cursor);
end if;
end;
end if;
Exchange.Set_Identity (Identity);
end Authenticate;
function Create
(Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return ACL.Backend'Class
is
Hash_Id_First : constant Hash_Id
:= (if Hash_Function_DB.Is_Empty
then Hash_Id'Last
else Hash_Function_DB.Query.Data.all'First);
Hash_Id_Last : constant Hash_Id
:= (if Hash_Function_DB.Is_Empty
then Hash_Id'First
else Hash_Function_DB.Query.Data.all'Last);
Builder : Backend_Builder (Hash_Id_First, Hash_Id_Last);
begin
case Arguments.Current_Event is
when S_Expressions.Events.Open_List =>
Read_DB (Arguments, Builder, Meaningless_Value);
when S_Expressions.Events.Add_Atom =>
declare
Reader : S_Expressions.File_Readers.S_Reader
:= S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Arguments.Current_Atom));
begin
Read_DB (Reader, Builder, Meaningless_Value);
end;
when others =>
Log (Severities.Error, "Unable to create ACL from S-expression"
& " starting with " & Arguments.Current_Event'Img);
end case;
return Result : Backend
:= (Map => Token_Maps.Create (Builder.Map),
Hashed => <>)
do
declare
Min : Hash_Id := Hash_Id'Last;
Max : Hash_Id := Hash_Id'First;
begin
for Id in Builder.Hashed'Range loop
if not Builder.Hashed (Id).Is_Empty then
-- Hash_Id'Min seems broken, using a basic `if` instead
if Id < Min then
Min := Id;
end if;
if Id > Max then
Max := Id;
end if;
end if;
end loop;
if Min <= Max then
declare
Data : constant Hashed_Token_Array_Refs.Data_Access
:= new Hashed_Token_Array (Min .. Max);
begin
Result.Hashed := Hashed_Token_Array_Refs.Create (Data);
for Id in Min .. Max loop
if not Builder.Hashed (Id).Is_Empty then
Data (Id) := Token_Maps.Create (Builder.Hashed (Id));
end if;
end loop;
end;
end if;
end;
end return;
end Create;
procedure Register
(Id : in Character;
Fn : in Hash_Function) is
begin
if Fn = null then
null;
elsif Hash_Function_DB.Is_Empty then
Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn));
elsif Id in Hash_Function_DB.Query.Data.all'Range then
Hash_Function_DB.Update.Data.all (Id) := Fn;
else
declare
New_First : constant Hash_Id
:= Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First);
New_Last : constant Hash_Id
:= Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last);
New_Data : constant Hash_Function_Array_Refs.Data_Access
:= new Hash_Function_Array'(New_First .. New_Last => null);
begin
New_Data (Hash_Function_DB.Query.Data.all'First
.. Hash_Function_DB.Query.Data.all'Last)
:= Hash_Function_DB.Query.Data.all;
New_Data (Id) := Fn;
Hash_Function_DB.Replace (New_Data);
end;
end if;
end Register;
end Natools.Web.ACL.Sx_Backends;
|
fix a bug when inserting the second hash function
|
acl-sx_backends: fix a bug when inserting the second hash function
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
186e854f43bd9e83e4ab9c1deec8fb180f36fe48
|
examples/draw/src/draw.adb
|
examples/draw/src/draw.adb
|
------------------------------------------------------------------------------
-- Bareboard drivers examples --
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
-- A very simple draw application.
-- Use your finger to draw pixels.
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
-- The "last chance handler" is the user-defined routine that is called when
-- an exception is propagated. We need it in the executable, therefore it
-- must be somewhere in the closure of the context clauses.
with STM32.Board; use STM32.Board;
with HAL.Bitmap; use HAL.Bitmap;
with HAL.Touch_Panel; use HAL.Touch_Panel;
with STM32.Button;
with Bitmapped_Drawing; use Bitmapped_Drawing;
procedure Draw
is
procedure Clear;
-----------
-- Clear --
-----------
procedure Clear is
begin
Display.Get_Hidden_Buffer (1).Fill ((Alpha => 255, others => 64));
end Clear;
begin
-- Initialize LCD
Display.Initialize;
Display.Initialize_Layer (1, RGB_888);
-- Initialize touch panel
Touch_Panel.Initialize;
-- Initialize button
STM32.Button.Initialize;
-- Clear LCD (set background)
Clear;
-- The application: set pixel where the finger is (so that you
-- cannot see what you are drawing).
loop
if STM32.Button.Has_Been_Pressed then
Clear;
else
declare
State : constant TP_State := Touch_Panel.Get_All_Touch_Points;
begin
for Touch of State loop
-- Workaround some strange readings from the STM32F429 TP
Fill_Circle
(Display.Get_Hidden_Buffer (1),
(Touch.X, Touch.Y), Touch.Weight / 4, HAL.Bitmap.Red);
Display.Update_Layer (1, Copy_Back => True);
end loop;
end;
end if;
end loop;
end Draw;
|
------------------------------------------------------------------------------
-- Bareboard drivers examples --
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
-- A very simple draw application.
-- Use your finger to draw pixels.
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
-- The "last chance handler" is the user-defined routine that is called when
-- an exception is propagated. We need it in the executable, therefore it
-- must be somewhere in the closure of the context clauses.
with STM32.Board; use STM32.Board;
with HAL.Bitmap; use HAL.Bitmap;
with HAL.Touch_Panel; use HAL.Touch_Panel;
with STM32.Button;
with Bitmapped_Drawing; use Bitmapped_Drawing;
procedure Draw
is
procedure Clear;
-----------
-- Clear --
-----------
procedure Clear is
begin
Display.Get_Hidden_Buffer (1).Fill ((Alpha => 255, others => 64));
Display.Update_Layer (1, Copy_Back => True);
end Clear;
Last_X : Integer := -1;
Last_Y : Integer := -1;
begin
-- Initialize LCD
Display.Initialize;
Display.Initialize_Layer (1, ARGB_8888);
-- Initialize touch panel
Touch_Panel.Initialize;
-- Initialize button
STM32.Button.Initialize;
-- Clear LCD (set background)
Clear;
-- The application: set pixel where the finger is (so that you
-- cannot see what you are drawing).
loop
if STM32.Button.Has_Been_Pressed then
Clear;
end if;
declare
State : constant TP_State := Touch_Panel.Get_All_Touch_Points;
begin
if State'Length = 0 then
Last_X := -1;
Last_Y := -1;
elsif State'Length = 1 then
-- Lines can be drawn between two consecutive points only when
-- one touch point is active: the order of the touch data is not
-- necessarily preserved by the hardware.
if Last_X > 0 then
Draw_Line
(Display.Get_Hidden_Buffer (1),
Start => (Last_X, Last_Y),
Stop => (State (State'First).X, State (State'First).Y),
Hue => HAL.Bitmap.Green,
Thickness => State (State'First).Weight / 2,
Fast => False);
end if;
Last_X := State (State'First).X;
Last_Y := State (State'First).Y;
else
Last_X := -1;
Last_Y := -1;
end if;
for Id in State'Range loop
Fill_Circle
(Display.Get_Hidden_Buffer (1),
Center => (State (Id).X, State (Id).Y),
Radius => State (Id).Weight / 4,
Hue => HAL.Bitmap.Green);
end loop;
if State'Length > 0 then
Display.Update_Layer (1, Copy_Back => True);
end if;
end;
end loop;
end Draw;
|
Improve the draw example: draws line between two consecutive touch
|
Improve the draw example: draws line between two consecutive touch
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
f1c23b5b94bf08a60c30e64491e2131cfe815917
|
src/asf-applications.adb
|
src/asf-applications.adb
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- 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 Util.Properties.Basic;
package body ASF.Applications is
-- ------------------------------
-- Get the configuration parameter;
-- ------------------------------
function Get (Self : Config;
Param : Config_Param) return String is
begin
return Self.Get (Param.Name.all, Param.Default.all);
end Get;
-- ------------------------------
-- Get the configuration parameter;
-- ------------------------------
function Get (Self : Config;
Param : Config_Param) return Boolean is
use Util.Properties.Basic.Boolean_Property;
begin
return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all));
end Get;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
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;
end ASF.Applications;
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 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.Properties.Basic;
package body ASF.Applications is
-- ------------------------------
-- Get the configuration parameter;
-- ------------------------------
function Get (Self : Config;
Param : Config_Param) return String is
begin
return Self.Get (Param.Name.all, Param.Default.all);
end Get;
-- ------------------------------
-- Get the configuration parameter;
-- ------------------------------
function Get (Self : Config;
Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String is
begin
if Self.Exists (Param.Name.all) then
return Self.Get (Param.Name.all);
else
return Ada.Strings.Unbounded.To_Unbounded_String (Param.Default.all);
end if;
end Get;
-- ------------------------------
-- Get the configuration parameter;
-- ------------------------------
function Get (Self : Config;
Param : Config_Param) return Boolean is
use Util.Properties.Basic.Boolean_Property;
begin
return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all));
end Get;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
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;
end ASF.Applications;
|
Implement new Get function that returns an Unbounded_String
|
Implement new Get function that returns an Unbounded_String
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
8ebde521e453e3605786ebe80f5381c4fd272dce
|
src/base/log/util-log.ads
|
src/base/log/util-log.ads
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001 - 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligible when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us. To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- == Logger Declaration ==
-- Similar to other logging framework such as Java Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- == Logger Messages ==
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are
-- replaced in the final message only when the message is enabled by the log configuration.
-- The use of parameters allows to avoid formatting the log message when the log is not used.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- The logger also provides a special `Error` procedure that accepts an Ada exception
-- occurrence as parameter. The exception name and message are printed together with
-- the error message. It is also possible to activate a complete traceback of the
-- exception and report it in the error message. With this mechanism, an exception
-- can be handled and reported easily:
--
-- begin
-- ...
-- exception
-- when E : others =>
-- Log.Error ("Something bad occurred", E, Trace => True);
-- end;
--
-- == Log Configuration ==
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
-- By default when the `layout` is not set or has an invalid value, the full message is
-- reported and the generated log messages will look as follows:
--
-- [2018-02-07 20:39:51] ERROR - X.Y - Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN - X.Y - The file test.txt is empty
-- [2018-02-07 20:39:51] INFO - X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG - X.Y - Reading line ......
--
-- When the `layout` configuration is set to `data-level-message`, the message is printed
-- with the date and message level.
--
-- [2018-02-07 20:39:51] ERROR: Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN : The file test.txt is empty
-- [2018-02-07 20:39:51] INFO : X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG: X.Y - Reading line ......
--
-- When the `layout` configuration is set to `level-message`, only the message and its
-- level are reported.
--
-- ERROR: Cannot open file test.txt: File does not exist
-- WARN : The file test.txt is empty
-- INFO : X.Y - Opening file test.txt
-- DEBUG: X.Y - Reading line ......
--
-- The last possible configuration for `layout` is `message` which only prints the message.
--
-- Cannot open file test.txt: File does not exist
-- The file test.txt is empty
-- Opening file test.txt
-- Reading line ......
--
-- The `Console` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | stderr | When 'true' or '1', use the console standard error, |
-- | | by default the appender uses the standard output |
--
-- The `File` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | File | The path used by the appender to create the output file. |
-- | append | When 'true' or '1', the file is opened in append mode otherwise |
-- | | it is truncated (the default is to truncate). |
-- | immediateFlush | When 'true' or '1', the file is flushed after each message log. |
-- | | Immediate flush is useful in some situations to have the log file |
-- | | updated immediately at the expense of slowing down the processing |
-- | | of logs. |
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001 - 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligible when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us. To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- == Logger Declaration ==
-- Similar to other logging framework such as Java Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- == Logger Messages ==
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are
-- replaced in the final message only when the message is enabled by the log configuration.
-- The use of parameters allows to avoid formatting the log message when the log is not used.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- The logger also provides a special `Error` procedure that accepts an Ada exception
-- occurrence as parameter. The exception name and message are printed together with
-- the error message. It is also possible to activate a complete traceback of the
-- exception and report it in the error message. With this mechanism, an exception
-- can be handled and reported easily:
--
-- begin
-- ...
-- exception
-- when E : others =>
-- Log.Error ("Something bad occurred", E, Trace => True);
-- end;
--
-- == Log Configuration ==
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
-- By default when the `layout` is not set or has an invalid value, the full message is
-- reported and the generated log messages will look as follows:
--
-- [2018-02-07 20:39:51] ERROR - X.Y - Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN - X.Y - The file test.txt is empty
-- [2018-02-07 20:39:51] INFO - X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG - X.Y - Reading line ......
--
-- When the `layout` configuration is set to `data-level-message`, the message is printed
-- with the date and message level.
--
-- [2018-02-07 20:39:51] ERROR: Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN : The file test.txt is empty
-- [2018-02-07 20:39:51] INFO : X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG: X.Y - Reading line ......
--
-- When the `layout` configuration is set to `level-message`, only the message and its
-- level are reported.
--
-- ERROR: Cannot open file test.txt: File does not exist
-- WARN : The file test.txt is empty
-- INFO : X.Y - Opening file test.txt
-- DEBUG: X.Y - Reading line ......
--
-- The last possible configuration for `layout` is `message` which only prints the message.
--
-- Cannot open file test.txt: File does not exist
-- The file test.txt is empty
-- Opening file test.txt
-- Reading line ......
--
-- @include util-log-appenders-consoles.ads
-- @include util-log-appenders-files.ads
-- @include util-log-appenders-rolling_files.ads
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
Add documentation for the configuration
|
Add documentation for the configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
613028da24a41e3611810e38cc56aeaede276e09
|
src/gen-commands-page.adb
|
src/gen-commands-page.adb
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
package body Gen.Commands.Page is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name);
use Ada.Strings.Unbounded;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Args.Get_Argument (1);
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
begin
if Args.Get_Count = 1 then
return "layout";
end if;
declare
Layout : constant String := Args.Get_Argument (2);
begin
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Info ("Layout file {0} not found.", Layout);
return Layout;
end;
end Get_Layout;
begin
if Args.Get_Count = 0 or Args.Get_Count > 2 then
Cmd.Usage (Name);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Get_Name);
Generator.Set_Global ("layout", Get_Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 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.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
package body Gen.Commands.Page is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
use Ada.Strings.Unbounded;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Args.Get_Argument (1);
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
begin
if Args.Get_Count = 1 then
return "layout";
end if;
declare
Layout : constant String := Args.Get_Argument (2);
begin
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Info ("Layout file {0} not found.", Layout);
return Layout;
end;
end Get_Layout;
begin
if Args.Get_Count = 0 or Args.Get_Count > 2 then
Cmd.Usage (Name);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Get_Name);
Generator.Set_Global ("layout", Get_Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
1bf422dc6949d3fdf4a63040b9be0af2d92ce86e
|
ARM/STMicro/STM32/components/lcd/rortech_stm32f7disco/stm32-lcd.ads
|
ARM/STMicro/STM32/components/lcd/rortech_stm32f7disco/stm32-lcd.ads
|
with STM32.LTDC;
with STM32.LCDInit;
package STM32.LCD is new
STM32.LTDC (LCD_Width => 480,
LCD_Height => 272,
LCD_HSync => 41,
LCD_HBP => 13,
LCD_HFP => 32,
LCD_VSYNC => 10,
LCD_VBP => 2,
LCD_VFP => 2,
PLLSAI_N => 429,
PLLSAI_R => 5,
DivR => 2,
Pre_LTDC_Initialize => STM32.LCDInit.Initialize,
Post_LTDC_Initialize => STM32.LCDInit.Post_Init);
|
with STM32.LTDC;
with STM32.LCDInit;
package STM32.LCD is new
STM32.LTDC (LCD_Width => 480,
LCD_Height => 272,
LCD_HSync => 41,
LCD_HBP => 13,
LCD_HFP => 32,
LCD_VSYNC => 10,
LCD_VBP => 2,
LCD_VFP => 2,
PLLSAI_N => 200,
PLLSAI_R => 5,
DivR => 2,
Pre_LTDC_Initialize => STM32.LCDInit.Initialize,
Post_LTDC_Initialize => STM32.LCDInit.Post_Init);
|
Fix LCD too slow on the STM32F7-Disco.
|
Fix LCD too slow on the STM32F7-Disco.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library
|
4c12cb0a33d53b4038682be125eaeafb3c2e8037
|
src/gen-commands-layout.adb
|
src/gen-commands-layout.adb
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := Get_Argument;
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Name : constant String := Get_Name;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
Update to use the new command implementation
|
Update to use the new command implementation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5da92f26697dd715b08ecd09c688e6e1b51f7974
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Html_Renderer);
-- 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 Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
procedure Add_Horizontal_Rule (Document : in out Html_Renderer);
-- Add a link.
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Html_Renderer);
-- 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 Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
Remove Add_Horizontal_Rule procedure
|
Remove Add_Horizontal_Rule procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
58f448c5fe1c73cd266b68b75488066c227ae912
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
-----------------------------------------------------------------------
-- awa-setup-applications -- Setup and installation
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
-- == Setup Procedure Instantiation==
-- The setup process is managed by the *Configure* generic procedure. The procedure must
-- be instantiated with the application class type and the application initialize procedure.
--
-- procedure Setup is
-- new AWA.Setup.Applications.Configure (MyApp.Application'Class,
-- MyApp.Application_Access,
-- MyApp.Initialize);
--
-- == Setup Operation ==
-- The *Setup* instantiated operation must then be called with the web container.
-- The web container is started first and the *Setup* procedure gets as parameter the
-- web container, the application instance to configure, the application name and
-- the application context path.
--
-- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH)
--
-- The operation will install the setup application to handle the setup actions. Through
-- the setup actions, the installer will be able to:
--
-- * Configure the database (MySQL or SQLite),
-- * Configure the Google+ and Facebook OAuth authentication keys,
-- * Configure the application name,
-- * Configure the mail parameters to be able to send email.
--
-- After the setup and configure is finished, the file <tt>.initialized</tt> is created in
-- the application directory to indicate the application is configured. The next time the
-- *Setup* operation is called, the installation process will be skipped.
--
-- To run again the installation, remove manually the <tt>.initialized</tt> file.
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup to start the application.
procedure Start (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and wait for the application to be started.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- awa-setup-applications -- Setup and installation
-- Copyright (C) 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with Servlet.Core.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
-- == Setup Procedure Instantiation==
-- The setup process is managed by the *Configure* generic procedure. The procedure must
-- be instantiated with the application class type and the application initialize procedure.
--
-- procedure Setup is
-- new AWA.Setup.Applications.Configure (MyApp.Application'Class,
-- MyApp.Application_Access,
-- MyApp.Initialize);
--
-- == Setup Operation ==
-- The *Setup* instantiated operation must then be called with the web container.
-- The web container is started first and the *Setup* procedure gets as parameter the
-- web container, the application instance to configure, the application name and
-- the application context path.
--
-- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH)
--
-- The operation will install the setup application to handle the setup actions. Through
-- the setup actions, the installer will be able to:
--
-- * Configure the database (MySQL or SQLite),
-- * Configure the Google+ and Facebook OAuth authentication keys,
-- * Configure the application name,
-- * Configure the mail parameters to be able to send email.
--
-- After the setup and configure is finished, the file <tt>.initialized</tt> is created in
-- the application directory to indicate the application is configured. The next time the
-- *Setup* operation is called, the installation process will be skipped.
--
-- To run again the installation, remove manually the <tt>.initialized</tt> file.
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new Servlet.Core.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased Servlet.Core.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup to start the application.
procedure Start (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and wait for the application to be started.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
Use the Servlet.Core package instread of ASF.Servlets
|
Use the Servlet.Core package instread of ASF.Servlets
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5f9c6bada6a24c73ce3b36cdd4bc8cce3db5e8e0
|
tools/druss-gateways.ads
|
tools/druss-gateways.ads
|
-----------------------------------------------------------------------
-- druss-gateways -- Gateway management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Properties;
with Util.Refs;
package Druss.Gateways is
type State_Type is (IDLE, READY, BUSY);
protected type Gateway_State is
function Get_State return State_Type;
private
State : State_Type := IDLE;
end Gateway_State;
type Gateway_Type is limited new Util.Refs.Ref_Entity with record
-- Gateway IP address.
Ip : Ada.Strings.Unbounded.Unbounded_String;
-- API password.
Passwd : Ada.Strings.Unbounded.Unbounded_String;
-- Directory that contains the images.
Images : Ada.Strings.Unbounded.Unbounded_String;
-- The gateway state.
State : Gateway_State;
-- Current WAN information (from api/v1/wan).
Wan : Util.Properties.Manager;
-- Current LAN information (from api/v1/lan).
Lan : Util.Properties.Manager;
-- Current Device information (from api/v1/device).
Device : Util.Properties.Manager;
end record;
type Gateway_Type_Access is access all Gateway_Type;
-- Refresh the information by using the Bbox API.
procedure Refresh (Gateway : in out Gateway_Type);
package Gateway_Refs is
new Util.Refs.References (Element_Type => Gateway_Type,
Element_Access => Gateway_Type_Access);
subtype Gateway_Ref is Gateway_Refs.Ref;
function "=" (Left, Right : in Gateway_Ref) return Boolean;
package Gateway_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Gateway_Ref,
"=" => "=");
subtype Gateway_Vector is Gateway_Vectors.Vector;
subtype Gateway_Cursor is Gateway_Vectors.Cursor;
-- Initalize the list of gateways from the property list.
procedure Initialize (Config : in Util.Properties.Manager;
List : in out Gateway_Vector);
-- Refresh the information by using the Bbox API.
procedure Refresh (Gateway : in Gateway_Ref)
with pre => not Gateway.Is_Null;
-- Iterate over the list of gateways and execute the <tt>Process</tt> procedure.
procedure Iterate (List : in Gateway_Vector;
Process : not null access procedure (G : in out Gateway_Type));
end Druss.Gateways;
|
-----------------------------------------------------------------------
-- druss-gateways -- Gateway management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Properties;
with Util.Refs;
with Bbox.API;
package Druss.Gateways is
type State_Type is (IDLE, READY, BUSY);
protected type Gateway_State is
function Get_State return State_Type;
private
State : State_Type := IDLE;
end Gateway_State;
type Gateway_Type is limited new Util.Refs.Ref_Entity with record
-- Gateway IP address.
Ip : Ada.Strings.Unbounded.Unbounded_String;
-- API password.
Passwd : Ada.Strings.Unbounded.Unbounded_String;
-- Directory that contains the images.
Images : Ada.Strings.Unbounded.Unbounded_String;
-- The gateway state.
State : Gateway_State;
-- Current WAN information (from api/v1/wan).
Wan : Util.Properties.Manager;
-- Current LAN information (from api/v1/lan).
Lan : Util.Properties.Manager;
-- Wireless information (From api/v1/wireless).
Wifi : Util.Properties.Manager;
-- Current Device information (from api/v1/device).
Device : Util.Properties.Manager;
-- The Bbox API client.
Client : Bbox.API.Client_Type;
end record;
type Gateway_Type_Access is access all Gateway_Type;
-- Refresh the information by using the Bbox API.
procedure Refresh (Gateway : in out Gateway_Type);
package Gateway_Refs is
new Util.Refs.References (Element_Type => Gateway_Type,
Element_Access => Gateway_Type_Access);
subtype Gateway_Ref is Gateway_Refs.Ref;
function "=" (Left, Right : in Gateway_Ref) return Boolean;
package Gateway_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Gateway_Ref,
"=" => "=");
subtype Gateway_Vector is Gateway_Vectors.Vector;
subtype Gateway_Cursor is Gateway_Vectors.Cursor;
-- Initalize the list of gateways from the property list.
procedure Initialize (Config : in Util.Properties.Manager;
List : in out Gateway_Vector);
-- Refresh the information by using the Bbox API.
procedure Refresh (Gateway : in Gateway_Ref)
with pre => not Gateway.Is_Null;
-- Iterate over the list of gateways and execute the <tt>Process</tt> procedure.
procedure Iterate (List : in Gateway_Vector;
Process : not null access procedure (G : in out Gateway_Type));
end Druss.Gateways;
|
Add wifi information to the Gateway object
|
Add wifi information to the Gateway object
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
67db3a96c04d3b616d1357a222d71bd30b82e75f
|
src/asf-responses-mockup.adb
|
src/asf-responses-mockup.adb
|
-----------------------------------------------------------------------
-- asf.responses -- ASF Requests
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Responses</b> package is an Ada implementation of
-- the Java servlet response (JSR 315 5. The Response).
package body ASF.Responses.Mockup is
-- ------------------------------
-- Adds the specified cookie to the response. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Resp : in out Response;
Cookie : in String) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- 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;
-- ------------------------------
-- 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
Resp.Headers.Insert (Name, Value);
end Add_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;
-- ------------------------------
-- Initialize the response mockup output stream.
-- ------------------------------
overriding
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (8192);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
end ASF.Responses.Mockup;
|
-----------------------------------------------------------------------
-- asf.responses -- ASF Requests
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Responses</b> package is an Ada implementation of
-- the Java servlet response (JSR 315 5. The Response).
package body ASF.Responses.Mockup is
-- ------------------------------
-- Adds the specified cookie to the response. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Resp : in out Response;
Cookie : in String) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- 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;
-- ------------------------------
-- 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
Resp.Headers.Insert (Name, Value);
end Add_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;
-- ------------------------------
-- 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;
|
Increase the response buffer for the mockup response
|
Increase the response buffer for the mockup response
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0ff917333c6f81ac38b5403ae3ce1b488f603cbe
|
src/asf-security-filters.ads
|
src/asf-security-filters.ads
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Policies; use Security;
with Servlet.Security.Filters;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
subtype Auth_Filter is Servlet.Security.Filters.Auth_Filter;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 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 Servlet.Security.Filters;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
subtype Auth_Filter is Servlet.Security.Filters.Auth_Filter;
end ASF.Security.Filters;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2426e5b820ec68d837e1b16d6d55c8b45eb9525b
|
src/gen-artifacts-docs-googlecode.adb
|
src/gen-artifacts-docs-googlecode.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
end Gen.Artifacts.Docs.Googlecode;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
end Gen.Artifacts.Docs.Googlecode;
|
Implement the Write_Line procedure
|
Implement the Write_Line procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
606680862fd9101b9921e25499761874815c5d41
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l:") is
when ASCII.NUL => exit;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: -web -tool -ado") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [-web] [-tool] [-ado] "
& "NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
New_Line;
Put_Line (" -web Generate a Web application");
Put_Line (" -tool Generate a command line tool");
Put_Line (" -ado Generate a database tool operation for ADO");
end Help;
end Gen.Commands.Project;
|
Add new options to create-project command to generate command line applications, database applications or web applications
|
Add new options to create-project command to generate command line
applications, database applications or web applications
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
3c2b8d40179ca014d0388b387ec1a318f542c55c
|
awa/src/awa-components-wikis.adb
|
awa/src/awa-components-wikis.adb
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Writers;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Raw (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write (Content);
end Write;
-- ------------------------------
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
-- ------------------------------
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Element (Name, Content);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Parsers.Wiki_Syntax_Type is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then
return Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.Parsers.SYNTAX_GOOGLE;
elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then
return Wiki.Parsers.SYNTAX_PHPBB;
elsif Format = "creole" or Format = "FORMAT_CREOLE" then
return Wiki.Parsers.SYNTAX_CREOLE;
elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then
return Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
return Wiki.Parsers.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Link_Renderer_Access;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Filter.Set_Document (Renderer'Unchecked_Access);
Renderer.Set_Writer (Html'Unchecked_Access);
Wiki.Parsers.Parse (Filter'Unchecked_Access,
Util.Beans.Objects.To_Wide_Wide_String (Value),
Format);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = IMAGE_PREFIX_ATTR then
From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
elsif Name = PAGE_PREFIX_ATTR then
From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
end if;
end Set_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
-- ------------------------------
-- Return true if the link is an absolute link.
-- ------------------------------
function Is_Link_Absolute (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String) return Boolean is
pragma Unreferenced (Renderer);
begin
return Element (Link, 1) = '/'
or else Starts_With (Link, "http://")
or else Starts_With (Link, "https://");
end Is_Link_Absolute;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Renderer.Is_Link_Absolute (Link) then
URI := Link;
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- 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 Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Helpers;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Streams.Html;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Raw (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then
return Wiki.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.SYNTAX_GOOGLE;
elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then
return Wiki.SYNTAX_PHPBB;
elsif Format = "creole" or Format = "FORMAT_CREOLE" then
return Wiki.SYNTAX_CREOLE;
elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then
return Wiki.SYNTAX_MEDIA_WIKI;
else
return Wiki.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Links.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Doc : Wiki.Documents.Document;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Links.Link_Renderer_Access;
Engine : Wiki.Parsers.Parser;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Format);
Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc);
Renderer.Set_Output_Stream (Html'Unchecked_Access);
Renderer.Render (Doc);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = IMAGE_PREFIX_ATTR then
From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
elsif Name = PAGE_PREFIX_ATTR then
From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
end if;
end Set_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Wiki.Helpers.Is_Url (Link) then
URI := To_Unbounded_Wide_Wide_String (Link);
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
Update the implementation to use the new Wiki API
|
Update the implementation to use the new Wiki API
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
92bc0dd713d9147a55ae155d58b4edd085c4e276
|
src/portscan.ads
|
src/portscan.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- GCC 6.0 only (skip Container_Checks until identified need arises)
pragma Suppress (Tampering_Check);
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
private with Replicant.Platform;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package EX renames Ada.Exceptions;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (catport : String; always_build : Boolean;
fatal : out Boolean)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
-- Return " (port deleted)" if the catport doesn't exist
-- Return " (directory empty)" if the directory exists but has no contents
-- Return " (Makefile missing)" when makefile is missing
-- otherwise return blank string
function obvious_problem (portsdir, catport : String) return String;
private
package REP renames Replicant;
package PLAT renames Replicant.Platform;
max_ports : constant := 32000;
scan_slave : constant builders := 9;
ss_base : constant String := "/SL09";
dir_ports : constant String := "/xports";
chroot : constant String := "/usr/sbin/chroot ";
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
pkg_dep_query : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
scan_locked : Boolean := False;
pkg_present : Boolean := False;
remote_pkg : Boolean := False;
never_remote : Boolean := False;
deletion_due : Boolean := False;
use_procfs : Boolean := False;
use_linprocfs : Boolean := False;
reverse_score : port_index := 0;
min_librun : Natural := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
portlist : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_set_depends (target : port_index;
catport : String;
line : JT.Text;
dtype : dependency_type);
procedure populate_set_options (target : port_index;
line : JT.Text;
on : Boolean);
procedure populate_port_data (target : port_index);
procedure populate_port_data_fpc (target : port_index);
procedure populate_port_data_nps (target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure wipe_make_queue;
procedure parallel_deep_scan (success : out Boolean;
show_progress : Boolean);
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_max_lots return scanners;
function get_pkg_name (origin : String) return String;
function timestamp (hack : CAL.Time; www_format : Boolean := False) return String;
function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
scan_start : CAL.Time;
scan_stop : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- GCC 6.0 only (skip Container_Checks until identified need arises)
pragma Suppress (Tampering_Check);
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
private with Replicant.Platform;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package EX renames Ada.Exceptions;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (catport : String; always_build : Boolean;
fatal : out Boolean)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
-- Return " (port deleted)" if the catport doesn't exist
-- Return " (directory empty)" if the directory exists but has no contents
-- Return " (Makefile missing)" when makefile is missing
-- otherwise return blank string
function obvious_problem (portsdir, catport : String) return String;
private
package REP renames Replicant;
package PLAT renames Replicant.Platform;
max_ports : constant := 40000;
scan_slave : constant builders := 9;
ss_base : constant String := "/SL09";
dir_ports : constant String := "/xports";
chroot : constant String := "/usr/sbin/chroot ";
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
pkg_dep_query : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
scan_locked : Boolean := False;
pkg_present : Boolean := False;
remote_pkg : Boolean := False;
never_remote : Boolean := False;
deletion_due : Boolean := False;
use_procfs : Boolean := False;
use_linprocfs : Boolean := False;
reverse_score : port_index := 0;
min_librun : Natural := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
portlist : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_set_depends (target : port_index;
catport : String;
line : JT.Text;
dtype : dependency_type);
procedure populate_set_options (target : port_index;
line : JT.Text;
on : Boolean);
procedure populate_port_data (target : port_index);
procedure populate_port_data_fpc (target : port_index);
procedure populate_port_data_nps (target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure wipe_make_queue;
procedure parallel_deep_scan (success : out Boolean;
show_progress : Boolean);
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_max_lots return scanners;
function get_pkg_name (origin : String) return String;
function timestamp (hack : CAL.Time; www_format : Boolean := False) return String;
function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
scan_start : CAL.Time;
scan_stop : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
Bump maximum ports to 40,000
|
Bump maximum ports to 40,000
FreeBSD is nearly at 32,000 now.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
d9e7360b92888f0c9f3ec48b645999da8064bb4d
|
src/util-log.ads
|
src/util-log.ads
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligeable when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us.
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- === Logger Declaration ===
-- Similar to other logging framework such as Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- === Logger Messages ===
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java MessageFormat class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- === Log Configuration ===
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
--
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligeable when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us.
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- == Logger Declaration ==
-- Similar to other logging framework such as Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- == Logger Messages ==
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are
-- replaced in the final message only when the message is enabled by the log configuration.
-- The use of parameters allows to avoid formatting the log message when the log is not used.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- The logger also provides a special `Error` procedure that accepts an Ada exception
-- occurence as parameter. The exception name and message are printed together with
-- the error message. It is also possible to activate a complete traceback of the
-- exception and report it in the error message. With this mechanism, an exception
-- can be handled and reported easily:
--
-- begin
-- ...
-- exception
-- when E : others =>
-- Log.Error ("Something bad occurred", E, Trace => True);
-- end;
--
-- == Log Configuration ==
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
--
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ce1a71d659cac55954e720a97d94ee2c7a7060f7
|
src/el-methods-proc_in.adb
|
src/el-methods-proc_in.adb
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_In -- Procedure Binding with 1 in argument
-- 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.
-----------------------------------------------------------------------
package body EL.Methods.Proc_In is
use EL.Expressions;
-- ------------------------------
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
-- ------------------------------
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is
begin
if Method.Binding = null then
return False;
else
return Method.Binding.all in Binding'Class;
end if;
end Is_Valid;
-- ------------------------------
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in Param1_Type) is
begin
if Method.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Method.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Method.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Method.Binding.all)'Access;
begin
Proxy.Method (Method.Object, Param);
end;
end Execute;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
Execute (Info, Param);
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type) is
Object : constant access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Methods.Proc_In;
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_In -- Procedure Binding with 1 in argument
-- Copyright (C) 2010, 2011, 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
package body EL.Methods.Proc_In is
use EL.Expressions;
-- ------------------------------
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
-- ------------------------------
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is
begin
if Method.Binding = null then
return False;
else
return Method.Binding.all in Binding'Class;
end if;
end Is_Valid;
-- ------------------------------
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in Param1_Type) is
begin
if Method.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Method.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Method.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Method.Binding.all)'Access;
begin
Proxy.Method (Util.Beans.Objects.To_Bean (Method.Object), Param);
end;
end Execute;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
Execute (Info, Param);
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type) is
Object : constant access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Methods.Proc_In;
|
Update use of Method_Info record after change of type for the Object member
|
Update use of Method_Info record after change of type for the Object member
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
48520191913df20b31e858e2a945c4dd0e5caf3d
|
mat/src/frames/mat-frames.adb
|
mat/src/frames/mat-frames.adb
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
with Util.Log.Loggers;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets");
procedure Split (F : in out Frame_Type;
Pos : in Positive);
procedure Add_Frame (F : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
function Check (Frame : in Frame_Type) return Boolean is
Parent : Frame_Type;
Child : Frame_Type;
Found : Boolean := False;
Result : Boolean := True;
begin
if Frame = null then
return False;
end if;
Parent := Frame.Parent;
if Parent /= null then
Child := Parent.Children;
while Child /= null loop
if Child = Frame then
Found := True;
end if;
if Child.Parent /= Parent then
Log.Error ("Invalid parent link");
Result := False;
end if;
Child := Child.Next;
end loop;
end if;
return Result;
end Check;
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- ------------------------------
-- Returns the backtrace of the current frame (up to the root).
-- ------------------------------
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Frame_Table (1 .. Frame.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Current /= null and Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- ------------------------------
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
-- ------------------------------
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
Child : Frame_Type;
begin
if Frame /= null then
Child := Frame.Children;
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
end if;
return Count;
end Count_Children;
-- ------------------------------
-- Returns all the direct calls made by the current frame.
-- ------------------------------
function Calls (Frame : in Frame_Type) return Frame_Table is
Nb_Calls : constant Natural := Count_Children (Frame);
Pc : Frame_Table (1 .. Nb_Calls);
begin
if Frame /= null then
declare
Child : Frame_Type := Frame.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
end;
end if;
return Pc;
end Calls;
-- ------------------------------
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
-- ------------------------------
function Current_Depth (Frame : in Frame_Type) return Natural is
begin
if Frame = null then
return 0;
else
return Frame.Depth;
end if;
end Current_Depth;
-- ------------------------------
-- Create a root for stack frame representation.
-- ------------------------------
function Create_Root return Frame_Type is
begin
return new Frame;
end Create_Root;
-- ------------------------------
-- Destroy the frame tree recursively.
-- ------------------------------
procedure Destroy (Frame : in out Frame_Type) is
F : Frame_Type;
begin
if Frame = null then
return;
end if;
-- Destroy its children recursively.
while Frame.Children /= null loop
F := Frame.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Frame.Parent /= null then
F := Frame.Parent.Children;
if F = Frame then
Frame.Parent.Children := Frame.Next;
else
while F /= null and then F.Next /= Frame loop
F := F.Next;
end loop;
if F = null then
Log.Error ("Frame is not linked to the correct parent");
return;
else
F.Next := Frame.Next;
end if;
end if;
end if;
Free (Frame);
end Destroy;
-- ------------------------------
-- Release the frame when its reference is no longer necessary.
-- ------------------------------
procedure Release (Frame : in Frame_Type) is
Current : Frame_Type := Frame;
begin
-- Scan the frame until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
Current.Used := Current.Used - 1;
if Current.Used = 0 then
declare
Tree : Frame_Type := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current := Current.Parent;
end if;
end loop;
end Release;
-- ------------------------------
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
-- ------------------------------
procedure Split (F : in out Frame_Type;
Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used - 1,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Type := F.Parent.Children;
begin
Log.Debug ("Split frame");
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
F.Used := F.Used - 1;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
if not Check (F) then
Log.Error ("Error when splitting frame");
end if;
end Split;
procedure Add_Frame (F : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type) is
Child : Frame_Type := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
if not Check (Child) then
Log.Error ("Error when adding frame");
end if;
end loop;
Result := Child;
end Add_Frame;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type) is
Current : Frame_Type := Frame;
Child : Frame_Type;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
else
Current.Used := Current.Used + 1;
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Current.Used := Current.Used + 1;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
function Find (Frame : in Frame_Type;
Pc : in Target_Addr) return Frame_Type is
Child : Frame_Type := Frame.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type is
Child : Frame_Type := Frame;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural) is
Current : Frame_Type := Frame;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search :
while Pos <= Pc'Last loop
declare
Addr : constant Target_Addr := Pc (Pos);
Child : Frame_Type := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
with Util.Log.Loggers;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets");
procedure Split (F : in out Frame_Type;
Pos : in Positive);
procedure Add_Frame (F : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
function Check (Frame : in Frame_Type) return Boolean is
Parent : Frame_Type;
Child : Frame_Type;
Found : Boolean := False;
Result : Boolean := True;
begin
if Frame = null then
return False;
end if;
Parent := Frame.Parent;
if Parent /= null then
Child := Parent.Children;
while Child /= null loop
if Child = Frame then
Found := True;
end if;
if Child.Parent /= Parent then
Log.Error ("Invalid parent link");
Result := False;
end if;
Child := Child.Next;
end loop;
end if;
return Result;
end Check;
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- ------------------------------
-- Returns the backtrace of the current frame (up to the root).
-- ------------------------------
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Frame_Table (1 .. Frame.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Current /= null and Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- ------------------------------
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
-- ------------------------------
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
Child : Frame_Type;
begin
if Frame /= null then
Child := Frame.Children;
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
end if;
return Count;
end Count_Children;
-- ------------------------------
-- Returns all the direct calls made by the current frame.
-- ------------------------------
function Calls (Frame : in Frame_Type) return Frame_Table is
Nb_Calls : constant Natural := Count_Children (Frame);
Pc : Frame_Table (1 .. Nb_Calls);
begin
if Frame /= null then
declare
Child : Frame_Type := Frame.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
end;
end if;
return Pc;
end Calls;
-- ------------------------------
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
-- ------------------------------
function Current_Depth (Frame : in Frame_Type) return Natural is
begin
if Frame = null then
return 0;
else
return Frame.Depth;
end if;
end Current_Depth;
-- ------------------------------
-- Create a root for stack frame representation.
-- ------------------------------
function Create_Root return Frame_Type is
begin
return new Frame;
end Create_Root;
-- ------------------------------
-- Destroy the frame tree recursively.
-- ------------------------------
procedure Destroy (Frame : in out Frame_Type) is
F : Frame_Type;
begin
if Frame = null then
return;
end if;
-- Destroy its children recursively.
while Frame.Children /= null loop
F := Frame.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Frame.Parent /= null then
F := Frame.Parent.Children;
if F = Frame then
Frame.Parent.Children := Frame.Next;
else
while F /= null and then F.Next /= Frame loop
F := F.Next;
end loop;
if F = null then
Log.Error ("Frame is not linked to the correct parent");
return;
else
F.Next := Frame.Next;
end if;
end if;
end if;
-- Free (Frame);
end Destroy;
-- ------------------------------
-- Release the frame when its reference is no longer necessary.
-- ------------------------------
procedure Release (Frame : in Frame_Type) is
Current : Frame_Type := Frame;
begin
-- Scan the frame until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Type := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- ------------------------------
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
-- ------------------------------
procedure Split (F : in out Frame_Type;
Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used - 1,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Type := F.Parent.Children;
begin
Log.Debug ("Split frame");
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
F.Used := F.Used - 1;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
if not Check (F) then
Log.Error ("Error when splitting frame");
end if;
end Split;
procedure Add_Frame (F : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type) is
Child : Frame_Type := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
if not Check (Child) then
Log.Error ("Error when adding frame");
end if;
end loop;
Result := Child;
end Add_Frame;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type) is
Current : Frame_Type := Frame;
Child : Frame_Type;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
Current.Used := Current.Used + 1;
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Current.Used := Current.Used + 1;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current.Used := Current.Used + 1;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
-- Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
function Find (Frame : in Frame_Type;
Pc : in Target_Addr) return Frame_Type is
Child : Frame_Type := Frame.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type is
Child : Frame_Type := Frame;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- ------------------------------
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
-- ------------------------------
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural) is
Current : Frame_Type := Frame;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search :
while Pos <= Pc'Last loop
declare
Addr : constant Target_Addr := Pc (Pos);
Child : Frame_Type := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
Fix frame management
|
Fix frame management
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
eed294cea9f824419ad0b53de0caeff65c5f9051
|
src/gen-model-mappings.ads
|
src/gen-model-mappings.ads
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
Nullable : 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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 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.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
Nullable : 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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
-- Get the type name.
function Get_Type_Name (From : Mapping_Definition) return String;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
Declare the Get_Type_Name function
|
Declare the Get_Type_Name function
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
99123d475d44010126e0f68d2db2ee94b38766de
|
src/util-strings-vectors.ads
|
src/util-strings-vectors.ads
|
-----------------------------------------------------------------------
-- Util-strings-vectors -- Vector of strings
-- 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.Containers.Indefinite_Vectors;
-- The <b>Util.Strings.Vectors</b> package provides an instantiation
-- of a vector container with Strings.
package Util.Strings.Vectors is new Ada.Containers.Indefinite_Vectors
(Element_Type => String,
Index_Type => Positive);
|
-----------------------------------------------------------------------
-- util-strings-vectors -- Vector of strings
-- Copyright (C) 2011, 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.Indefinite_Vectors;
-- The <b>Util.Strings.Vectors</b> package provides an instantiation
-- of a vector container with Strings.
package Util.Strings.Vectors is new Ada.Containers.Indefinite_Vectors
(Element_Type => String,
Index_Type => Positive);
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
31246f7000005a6928f104bf8da9758fb39953f5
|
src/http/aws/util-http-clients-web.ads
|
src/http/aws/util-http-clients-web.ads
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with null record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
type AWS_Http_Request is new Http_Request with record
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String;
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
end Util.Http.Clients.Web;
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
private with AWS.Client;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with record
Timeout : Duration := 60.0;
end record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
type AWS_Http_Request is new Http_Request with record
Timeouts : AWS.Client.Timeouts_Values := AWS.Client.No_Timeout;
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String;
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
end Util.Http.Clients.Web;
|
Add timeouts to the HTTP requests
|
Add timeouts to the HTTP requests
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9fecba58e8a94ca23eb4784e0f88dfafebc0f2bd
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
end if;
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
-- Post.Title := Post.Post.Get_Title;
-- Post.Text := Post.Post.Get_Text;
-- Post.URI := Post.Post.Get_Uri;
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- Create the Post_List_Bean bean instance.
-- ------------------------------
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- Get a select item list which contains a list of post status.
-- ------------------------------
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
Result := Bean.Get_Id;
end if;
Bean.Tags.Update_Tags (Result);
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
elsif Name = POST_TAG_ATTR then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
Post.Tags.Load_Tags (Session, Id);
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Blogs.Models.POST_TABLE);
Object.Tags.Set_Permission ("blog-update-post");
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- Create the Post_List_Bean bean instance.
-- ------------------------------
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- Get a select item list which contains a list of post status.
-- ------------------------------
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
end AWA.Blogs.Beans;
|
Update the tags associated with a post after the post is saved or created Load the tags associated with the post.
|
Update the tags associated with a post after the post is saved or created
Load the tags associated with the post.
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6f77ff599b870e26073aa776a3adeef5e4158479
|
regtests/ado-drivers-tests.adb
|
regtests/ado-drivers-tests.adb
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test the Initialize operation.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
begin
ADO.Drivers.Initialize ("test-missing-config.properties");
end Test_Initialize;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
Controller.Set_Property ("password", "test");
Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"),
"Invalid 'password' property for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2");
Check ("sqlite:///test.db", "", 0, "test.db");
Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
end ADO.Drivers.Tests;
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Test_Caller;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test the Initialize operation.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
begin
ADO.Drivers.Initialize ("test-missing-config.properties");
end Test_Initialize;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
Controller.Set_Property ("password", "test");
Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"),
"Invalid 'password' property for " & URI);
exception
when E : Connection_Error =>
Util.Tests.Assert_Matches (T, "Driver.*not found.*",
Ada.Exceptions.Exception_Message (E),
"Invalid exception raised for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2");
Check ("sqlite:///test.db", "", 0, "test.db");
Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
end ADO.Drivers.Tests;
|
Fix the Set_Connection test when a driver is not supported
|
Fix the Set_Connection test when a driver is not supported
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
cc668418ee1a425d645eca83a3c5b02db32ea06f
|
regtests/util-locales-tests.adb
|
regtests/util-locales-tests.adb
|
-----------------------------------------------------------------------
-- util-locales-tests -- Unit tests for locales
-- Copyright (C) 2009, 2010, 2011, 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.Test_Caller;
package body Util.Locales.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Locales");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Language",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Country",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Hash",
Test_Hash_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.=",
Test_Compare_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Locales",
Test_Get_Locales'Access);
Caller.Add_Test (Suite, "Test Util.Locales.NULL_LOCALE",
Test_Null_Locale'Access);
end Add_Tests;
procedure Test_Get_Locale (T : in out Test) is
Loc : Locale;
begin
Loc := Get_Locale ("en");
Assert_Equals (T, "en", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "eng", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("ar_DZ");
Assert_Equals (T, "ar", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "DZ", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "DZA", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "ara", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("fr");
Assert_Equals (T, "fr", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "fra", Get_ISO3_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_ISO3_Country (Loc), "Invalid country");
Loc := Get_Locale ("ja", "JP", "JP");
Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "JPN", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "jpn_JP", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("no", "NO", "NY");
Assert_Equals (T, "no", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant");
end Test_Get_Locale;
procedure Test_Hash_Locale (T : in out Test) is
use type Ada.Containers.Hash_Type;
begin
T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different");
T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different");
T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different");
end Test_Hash_Locale;
procedure Test_Compare_Locale (T : in out Test) is
begin
T.Assert (FRANCE /= FRENCH, "Equality");
T.Assert (FRANCE = FRANCE, "Equality");
T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality");
T.Assert (FRANCE /= ENGLISH, "Equality");
T.Assert (FRENCH /= ENGLISH, "Equaliy");
end Test_Compare_Locale;
procedure Test_Get_Locales (T : in out Test) is
begin
for I in Locales'Range loop
declare
Language : constant String := Get_Language (Locales (I));
Country : constant String := Get_Country (Locales (I));
Variant : constant String := Get_Variant (Locales (I));
Loc : constant Locale := Get_Locale (Language, Country, Variant);
Name : constant String := To_String (Loc);
Iso : constant String := Get_ISO3_Language (Locales (I));
Iso_Country : constant String := Get_ISO3_Country (Locales (I));
begin
T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I)
& " " & Loc.all);
if Variant'Length > 0 then
Assert_Equals (T, Name, Language & "_" & Country & "_" & Variant,
"Invalid To_String");
elsif Country'Length > 0 then
Assert_Equals (T, Name, Language & "_" & Country, "Invalid To_String");
else
Assert_Equals (T, Name, Language, "Invalid To_String");
end if;
end;
end loop;
end Test_Get_Locales;
procedure Test_Null_Locale (T : in out Test) is
Loc : Locale;
begin
Assert_Equals (T, "", Get_Language (NULL_LOCALE), "Invalid language");
Assert_Equals (T, "", Get_ISO3_Language (NULL_LOCALE), "Invalid language");
Assert_Equals (T, "", To_String (NULL_LOCALE), "Invalid To_String");
Loc := Get_Locale ("", "");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("xz", "");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("en", "blob");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("xx");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("en", "de", "plop");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
end Test_Null_Locale;
end Util.Locales.Tests;
|
-----------------------------------------------------------------------
-- util-locales-tests -- Unit tests for locales
-- Copyright (C) 2009, 2010, 2011, 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.Test_Caller;
package body Util.Locales.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Locales");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Language",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Country",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Hash",
Test_Hash_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.=",
Test_Compare_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Locales",
Test_Get_Locales'Access);
Caller.Add_Test (Suite, "Test Util.Locales.NULL_LOCALE",
Test_Null_Locale'Access);
end Add_Tests;
procedure Test_Get_Locale (T : in out Test) is
Loc : Locale;
begin
Loc := Get_Locale ("en");
Assert_Equals (T, "en", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "eng", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("ar_DZ");
Assert_Equals (T, "ar", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "DZ", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "DZA", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "ara", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("fr");
Assert_Equals (T, "fr", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "fra", Get_ISO3_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_ISO3_Country (Loc), "Invalid country");
Loc := Get_Locale ("ja", "JP", "JP");
Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant");
Assert_Equals (T, "JPN", Get_ISO3_Country (Loc), "Invalid country");
Assert_Equals (T, "jpn_JP", Get_ISO3_Language (Loc), "Invalid language");
Loc := Get_Locale ("no", "NO", "NY");
Assert_Equals (T, "no", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant");
end Test_Get_Locale;
procedure Test_Hash_Locale (T : in out Test) is
use type Ada.Containers.Hash_Type;
begin
T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different");
T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different");
T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different");
end Test_Hash_Locale;
procedure Test_Compare_Locale (T : in out Test) is
begin
T.Assert (FRANCE /= FRENCH, "Equality");
T.Assert (FRANCE = FRANCE, "Equality");
T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality");
T.Assert (FRANCE /= ENGLISH, "Equality");
T.Assert (FRENCH /= ENGLISH, "Equaliy");
end Test_Compare_Locale;
procedure Test_Get_Locales (T : in out Test) is
begin
for I in Locales'Range loop
declare
Language : constant String := Get_Language (Locales (I));
Country : constant String := Get_Country (Locales (I));
Variant : constant String := Get_Variant (Locales (I));
Loc : constant Locale := Get_Locale (Language, Country, Variant);
Name : constant String := To_String (Loc);
Iso : constant String := Get_ISO3_Language (Locales (I));
Iso_Country : constant String := Get_ISO3_Country (Locales (I));
pragma Unreferenced (Iso, Iso_Country);
begin
T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I)
& " " & Loc.all);
if Variant'Length > 0 then
Assert_Equals (T, Name, Language & "_" & Country & "_" & Variant,
"Invalid To_String");
elsif Country'Length > 0 then
Assert_Equals (T, Name, Language & "_" & Country, "Invalid To_String");
else
Assert_Equals (T, Name, Language, "Invalid To_String");
end if;
end;
end loop;
end Test_Get_Locales;
procedure Test_Null_Locale (T : in out Test) is
Loc : Locale;
begin
Assert_Equals (T, "", Get_Language (NULL_LOCALE), "Invalid language");
Assert_Equals (T, "", Get_ISO3_Language (NULL_LOCALE), "Invalid language");
Assert_Equals (T, "", To_String (NULL_LOCALE), "Invalid To_String");
Loc := Get_Locale ("", "");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("xz", "");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("en", "blob");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("xx");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
Loc := Get_Locale ("en", "de", "plop");
T.Assert (Loc = NULL_LOCALE, "Invalid Get_Locale");
end Test_Null_Locale;
end Util.Locales.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c7401dc7370bc79565ef757a1f5cef2164b35bd5
|
src/sys/encoders/util-encoders-hmac-sha1.ads
|
src/sys/encoders/util-encoders-hmac-sha1.ads
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA1;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA1 is
pragma Preelaborate;
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest;
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest;
-- ------------------------------
-- HMAC-SHA1 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False);
-- ------------------------------
-- HMAC-SHA1 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Util.Encoders.Transformer with null record;
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA1.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA1;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2012, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA1;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA1 is
pragma Preelaborate;
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA1.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest;
-- ------------------------------
-- HMAC-SHA1 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False);
-- ------------------------------
-- HMAC-SHA1 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Util.Encoders.Transformer with null record;
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA1.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA1;
|
Declare Sign procedure for PBKDF2
|
Declare Sign procedure for PBKDF2
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
22ef7ca0d4af4133685dfddfc8ad6d9df697c01d
|
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 abstract new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String is abstract;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
-----------------------------------------------------------------------
-- 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;
-- == Security Policies ==
--
-- @include security-policies-roles.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;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
58161ebdf60197589d67228b6a5d28e1de04f362
|
awa/samples/src/atlas-applications.adb
|
awa/samples/src/atlas-applications.adb
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 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.IO_Exceptions;
with GNAT.MD5;
with Util.Log.Loggers;
with Util.Properties;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (0);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- 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;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access) is
Fact : AWA.Applications.Factory.Application_Factory;
C : ASF.Applications.Config;
begin
App.Self := App;
begin
C.Load_Properties ("atlas.properties");
Util.Log.Loggers.Initialize (Util.Properties.Manager (C));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with GNAT.MD5;
with Util.Log.Loggers;
with Util.Properties;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (0);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- 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;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access) is
Fact : AWA.Applications.Factory.Application_Factory;
C : ASF.Applications.Config;
begin
App.Self := App;
begin
C.Load_Properties ("atlas.properties");
Util.Log.Loggers.Initialize (Util.Properties.Manager (C));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
Fix compilation error with GNAT 2015
|
Fix compilation error with GNAT 2015
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
08a7858fdeb2b875a4eb47b255ca6ae3fa6b40f7
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Wiki_Space (Bean);
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
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.
-----------------------------------------------------------------------
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Wiki_Space (Bean);
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki page.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
if Bean.Is_Inserted then
Bean.Service.Save (Bean);
else
Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean);
end if;
end Save;
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Page_Bean;
end AWA.Wikis.Beans;
|
Implement the Wiki_Page_Bean operations
|
Implement the Wiki_Page_Bean operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a590b3db0ec908c99f3eb9050d72678fc83f4f46
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- 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);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- 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);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- 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);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- 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);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Add a Search_Path to the Target_Symbols record
|
Add a Search_Path to the Target_Symbols record
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
59788cd1d1469b09a5ab6d310a313a184778496a
|
mat/src/mat-targets.adb
|
mat/src/mat-targets.adb
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Memory.Targets.Initialize (Memory => Target.Memory,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Target.Processes.Insert (Pid, Process);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Target.Processes.Insert (Pid, Process);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
Update Initialize to setup and initialize the process probe servant
|
Update Initialize to setup and initialize the process probe servant
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
37b63684faab7b4ac648a896a5ff353946139a23
|
src/asf-security-filters.ads
|
src/asf-security-filters.ads
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Permissions; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Permissions.Permission_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Permissions.Permission_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Policies; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Policies.Policy_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
Update after Security package refactorisation
|
Update after Security package refactorisation
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
e39c18f606a3cd69bcf6d8c926a8cf0e8055de30
|
samples/multipro_refs.adb
|
samples/multipro_refs.adb
|
-----------------------------------------------------------------------
-- multipro_refs -- Points out multiprocessor issues with reference counters
-- 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.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
with Util.Refs;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
procedure Multipro_Refs is
use Util.Log;
use Util.Concurrent.Counters;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
type Data is new Util.Refs.Ref_Entity with record
Value : Natural;
Rand : Natural;
Result : Long_Long_Integer;
end record;
type Data_Access is access all Data;
package Data_Ref is new Util.Refs.References (Data, Data_Access);
package Hash_Map is new Ada.Containers.Indefinite_Hashed_Maps (String, String,
Ada.Strings.Hash,
"=");
type Cache is new Util.Refs.Ref_Entity with record
Map : Hash_Map.Map;
end record;
type Cache_Access is access all Cache;
package Hash_Ref is new Util.Refs.References (Cache, Cache_Access);
procedure Set_Reference (O : in Data_Ref.Ref);
function Exists (Key : in String) return Boolean;
function Find (Key : in String) return String;
procedure Add (Key : in String; Value : in String);
function Get_Reference return Data_Ref.Ref;
R : Hash_Ref.Atomic_Ref;
function Exists (Key : in String) return Boolean is
C : constant Hash_Ref.Ref := R.Get;
begin
return C.Value.Map.Contains (Key);
end Exists;
function Find (Key : in String) return String is
C : constant Hash_Ref.Ref := R.Get;
begin
if C.Value.Map.Contains (Key) then
return C.Value.Map.Element (Key);
else
return "";
end if;
end Find;
procedure Add (Key : in String; Value : in String) is
C : constant Hash_Ref.Ref := R.Get;
N : constant Hash_Ref.Ref := Hash_Ref.Create;
begin
N.Value.all.Map := C.Value.Map;
N.Value.all.Map.Include (Key, Value);
R.Set (N);
end Add;
-- Target counter value we would like.
Max_Counter : constant Integer := 1_00_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
Unsafe_Ref : Data_Ref.Ref := Data_Ref.Create;
Safe_Ref : Data_Ref.Atomic_Ref;
-- When <b>Run_Safe</b> is false, we use the Ada assignment to update a reference.
-- The program will crash at a random time due to corruption or multiple free.
--
-- When <b>Run_Safe</b> is true, we use the protected type Atomic_Ref to change
-- the shared reference. It will not crash.
Run_Safe : constant Boolean := True;
function Get_Reference return Data_Ref.Ref is
begin
if Run_Safe then
return Safe_Ref.Get;
else
return Unsafe_Ref;
end if;
end Get_Reference;
procedure Set_Reference (O : in Data_Ref.Ref) is
begin
if Run_Safe then
Safe_Ref.Set (O);
else
Unsafe_Ref := O;
end if;
end Set_Reference;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
Safe_Ref.Set (Data_Ref.Create);
Get_Reference.Value.all.Value := 0;
for Task_Count in 1 .. Max_Tasks loop
R.Set (Hash_Ref.Create);
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural;
Ident : in Integer);
end Worker;
task body Worker is
Cnt : Natural;
Id : Integer;
begin
accept Start (Count : in Natural;
Ident : in Integer) do
Cnt := Count;
Id := Ident;
end Start;
-- Get the data, compute something and change the reference.
for I in 1 .. Cnt loop
declare
Ref : constant Data_Ref.Ref := Get_Reference;
Ref2 : constant Data_Ref.Ref := Data_Ref.Create;
Key : constant String := "K" & Natural'Image (I / 10);
begin
Ref2.Value.all.Value := Ref.Value.all.Value + 1;
Ref2.Value.all.Rand := Cnt;
Ref2.Value.all.Result := Long_Long_Integer (Ref2.Value.all.Rand * Cnt)
* Long_Long_Integer (Ref2.Value.all.Value);
Set_Reference (Ref2);
Util.Concurrent.Counters.Increment (Counter);
if not Exists (Key) then
Add (Key, Natural'Image (I));
end if;
declare
S : constant String := Find (Key);
pragma Unreferenced (S);
begin
null;
exception
when others =>
Log.Info ("{0}: Find did not found the key: {1}",
Integer'Image (Id), Key);
end;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised: ", E, True);
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task, I);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
Log.Info ("Data.Value := " & Natural'Image (Get_Reference.Value.all.Value));
Log.Info ("Data.Rand := " & Natural'Image (Get_Reference.Value.all.Rand));
Log.Info ("Data.Result := " & Long_Long_Integer'Image (Get_Reference.Value.all.Result));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro_Refs;
|
-----------------------------------------------------------------------
-- multipro_refs -- Points out multiprocessor issues with reference counters
-- 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 Util.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
with Util.Refs;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
procedure Multipro_Refs is
use Util.Log;
use Util.Concurrent.Counters;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
type Data is new Util.Refs.Ref_Entity with record
Value : Natural;
Rand : Natural;
Result : Long_Long_Integer;
end record;
type Data_Access is access all Data;
package Data_Ref is new Util.Refs.References (Data, Data_Access);
package Atomic_Data_Ref is new Data_Ref.IR.Atomic;
package Hash_Map is new Ada.Containers.Indefinite_Hashed_Maps (String, String,
Ada.Strings.Hash,
"=");
type Cache is new Util.Refs.Ref_Entity with record
Map : Hash_Map.Map;
end record;
type Cache_Access is access all Cache;
package Hash_Ref is new Util.Refs.References (Cache, Cache_Access);
package Atomic_Hash_Ref is new Hash_Ref.IR.Atomic;
procedure Set_Reference (O : in Data_Ref.Ref);
function Exists (Key : in String) return Boolean;
function Find (Key : in String) return String;
procedure Add (Key : in String; Value : in String);
function Get_Reference return Data_Ref.Ref;
R : Atomic_Hash_Ref.Atomic_Ref;
function Exists (Key : in String) return Boolean is
C : constant Hash_Ref.Ref := R.Get;
begin
return C.Value.Map.Contains (Key);
end Exists;
function Find (Key : in String) return String is
C : constant Hash_Ref.Ref := R.Get;
begin
if C.Value.Map.Contains (Key) then
return C.Value.Map.Element (Key);
else
return "";
end if;
end Find;
procedure Add (Key : in String; Value : in String) is
C : constant Hash_Ref.Ref := R.Get;
N : constant Hash_Ref.Ref := Hash_Ref.Create;
begin
N.Value.Map := C.Value.Map;
N.Value.Map.Include (Key, Value);
R.Set (N);
end Add;
-- Target counter value we would like.
Max_Counter : constant Integer := 1_00_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
Unsafe_Ref : Data_Ref.Ref := Data_Ref.Create;
Safe_Ref : Atomic_Data_Ref.Atomic_Ref;
-- When <b>Run_Safe</b> is false, we use the Ada assignment to update a reference.
-- The program will crash at a random time due to corruption or multiple free.
--
-- When <b>Run_Safe</b> is true, we use the protected type Atomic_Ref to change
-- the shared reference. It will not crash.
Run_Safe : constant Boolean := True;
function Get_Reference return Data_Ref.Ref is
begin
if Run_Safe then
return Safe_Ref.Get;
else
return Unsafe_Ref;
end if;
end Get_Reference;
procedure Set_Reference (O : in Data_Ref.Ref) is
begin
if Run_Safe then
Safe_Ref.Set (O);
else
Unsafe_Ref := O;
end if;
end Set_Reference;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
Safe_Ref.Set (Data_Ref.Create);
Get_Reference.Value.Value := 0;
for Task_Count in 1 .. Max_Tasks loop
R.Set (Hash_Ref.Create);
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural;
Ident : in Integer);
end Worker;
task body Worker is
Cnt : Natural;
Id : Integer;
begin
accept Start (Count : in Natural;
Ident : in Integer) do
Cnt := Count;
Id := Ident;
end Start;
-- Get the data, compute something and change the reference.
for I in 1 .. Cnt loop
declare
Ref : constant Data_Ref.Ref := Get_Reference;
Ref2 : constant Data_Ref.Ref := Data_Ref.Create;
Key : constant String := "K" & Natural'Image (I / 10);
begin
Ref2.Value.Value := Ref.Value.Value + 1;
Ref2.Value.Rand := Cnt;
Ref2.Value.Result := Long_Long_Integer (Ref2.Value.Rand * Cnt)
* Long_Long_Integer (Ref2.Value.Value);
Set_Reference (Ref2);
Util.Concurrent.Counters.Increment (Counter);
if not Exists (Key) then
Add (Key, Natural'Image (I));
end if;
declare
S : constant String := Find (Key);
pragma Unreferenced (S);
begin
null;
exception
when others =>
Log.Info ("{0}: Find did not found the key: {1}",
Integer'Image (Id), Key);
end;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised: ", E, True);
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task, I);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
Log.Info ("Data.Value := " & Natural'Image (Get_Reference.Value.Value));
Log.Info ("Data.Rand := " & Natural'Image (Get_Reference.Value.Rand));
Log.Info ("Data.Result := " & Long_Long_Integer'Image (Get_Reference.Value.Result));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro_Refs;
|
Fix sample with implementation of Util.Refs with Implicit_Dereference
|
Fix sample with implementation of Util.Refs with Implicit_Dereference
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e3119d369fdbaeb7275dcd11971cba1216d655e5
|
src/wiki.ads
|
src/wiki.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- 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.
-----------------------------------------------------------------------
-- == Wiki ==
-- The Wiki engine parses a Wiki text in several Wiki syntax such as <tt>MediaWiki</tt>,
-- <tt>Creole</tt>, <tt>Markdown</tt> and renders the result either in HTML, text or into
-- another Wiki format. The Wiki engine is used in two steps:
--
-- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance.
-- * The Wiki document is then rendered by a renderer to produce the final HTML, text.
--
-- @include wiki-documents.ads
-- @include wiki-attributes.ads
-- @include wiki-parsers.ads
package Wiki is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Defines the possible text formats.
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag is
(
-- Section 4.1 The root element
ROOT_HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag) return String_Access;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
end Wiki;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- 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.
-----------------------------------------------------------------------
-- == Wiki ==
-- The Wiki engine parses a Wiki text in several Wiki syntax such as <tt>MediaWiki</tt>,
-- <tt>Creole</tt>, <tt>Markdown</tt> and renders the result either in HTML, text or into
-- another Wiki format. The Wiki engine is used in two steps:
--
-- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance.
-- * The Wiki document is then rendered by a renderer to produce the final HTML, text.
--
-- [images/ada-wiki.png]
--
-- The Ada Wiki engine is organized in several packages:
--
-- * The Wiki stream packages define the interface, types and operations for the Wiki
-- engine to read the Wiki or HTML content and for the Wiki renderer to generate the
-- HTML or text outputs.
-- * The Wiki parser is responsible for parsing HTML or Wiki content according to a
-- selected Wiki syntax. It builds the final Wiki document through filters and plugins.
-- * The Wiki filters provides a simple filter framework that allows to plug specific
-- filters when a Wiki document is parsed and processed. Filters are used for the
-- table of content generation, for the HTML filtering, to collect words or links
-- and so on.
-- * The Wiki plugins defines the plugin interface that is used by the Wiki engine
-- to provide pluggable extensions in the Wiki. Plugins are used for the Wiki template
-- support, to hide some Wiki text content when it is rendered or to interact with
-- other systems.
-- * The Wiki documents and attributes are used for the representation of the Wiki
-- document after the Wiki content is parsed.
-- * The Wiki renderers are the last packages which are used for the rendering of the
-- Wiki document to produce the final HTML or text.
--
-- @include wiki-documents.ads
-- @include wiki-attributes.ads
-- @include wiki-parsers.ads
package Wiki is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Defines the possible text formats.
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag is
(
-- Section 4.1 The root element
ROOT_HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag) return String_Access;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
end Wiki;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
375bbace8732c5271f24bdf628ab9226caa025d2
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "0";
raven_version_minor : constant String := "55";
copyright_years : constant String := "2015-2017";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.24";
default_pgsql : constant String := "9.6";
default_python3 : constant String := "3.5";
default_ruby : constant String := "2.4";
default_tcltk : constant String := "8.6";
default_compiler : constant String := "gcc6";
compiler_version : constant String := "6.20170202";
arc_ext : constant String := ".txz";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "0";
raven_version_minor : constant String := "56";
copyright_years : constant String := "2015-2017";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.24";
default_pgsql : constant String := "9.6";
default_python3 : constant String := "3.5";
default_ruby : constant String := "2.4";
default_tcltk : constant String := "8.6";
default_compiler : constant String := "gcc6";
compiler_version : constant String := "6.20170202";
arc_ext : constant String := ".txz";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version to 0.56
|
Bump version to 0.56
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
909db8bef361458ddce48f714b364ec2e560e983
|
regtests/wiki-tests.adb
|
regtests/wiki-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Autolink;
with Wiki.Filters.Variables;
with Wiki.Plugins.Templates;
with Wiki.Plugins.Conditions;
with Wiki.Plugins.Variables;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter;
Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin;
Variables : aliased Wiki.Plugins.Variables.Variable_Plugin;
List_Vars : aliased Wiki.Plugins.Variables.List_Variable_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record;
-- Find a plugin knowing its name.
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access;
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is
pragma Unreferenced (Factory);
begin
if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then
return Condition'Unchecked_Access;
elsif Name = "set" then
return Variables'Unchecked_Access;
elsif Name = "list" then
return List_Vars'Unchecked_Access;
else
return Template.Find (Name);
end if;
end Find;
Local_Factory : aliased Test_Factory;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
Condition.Append ("public", "");
Condition.Append ("user", "admin");
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Auto_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Add_Filter (Var_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML or T.Is_Cvt 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;
procedure Add_Convert_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MARKDOWN =>
Tst := Create_Test (Name & ".markdown", 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;
procedure Add_Convert_Tests is
Dir : constant String := "regtests/files/convert";
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);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_MARKDOWN =>
Tst := Create_Test (Name & ".markdown", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Is_Cvt := True;
Tst.Source := Format;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Convert_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
Add_Convert_Tests;
end Add_Tests;
end Wiki.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Util.Measures;
with Wiki.Strings;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Autolink;
with Wiki.Filters.Variables;
with Wiki.Plugins.Templates;
with Wiki.Plugins.Conditions;
with Wiki.Plugins.Variables;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter;
Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin;
Variables : aliased Wiki.Plugins.Variables.Variable_Plugin;
List_Vars : aliased Wiki.Plugins.Variables.List_Variable_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record;
-- Find a plugin knowing its name.
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access;
overriding
function Find (Factory : in Test_Factory;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is
pragma Unreferenced (Factory);
begin
if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then
return Condition'Unchecked_Access;
elsif Name = "set" then
return Variables'Unchecked_Access;
elsif Name = "list" then
return List_Vars'Unchecked_Access;
else
return Template.Find (Name);
end if;
end Find;
Local_Factory : aliased Test_Factory;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
Condition.Append ("public", "");
Condition.Append ("user", "admin");
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Auto_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Add_Filter (Var_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Var_Filter.Add_Variable (String '("file"), Wiki.Strings.To_WString (To_String (T.Name)));
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML or T.Is_Cvt 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;
procedure Add_Convert_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MARKDOWN =>
Tst := Create_Test (Name & ".markdown", 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;
procedure Add_Convert_Tests is
Dir : constant String := "regtests/files/convert";
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);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
elsif Ext = "markdown" then
Format := Wiki.SYNTAX_MARKDOWN;
else
Format := Wiki.SYNTAX_MIX;
end if;
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when Wiki.SYNTAX_MARKDOWN =>
Tst := Create_Test (Name & ".markdown", Path & "/" & Simple,
Syntax, "/wiki-convert/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Is_Cvt := True;
Tst.Source := Format;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Convert_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
Add_Convert_Tests;
end Add_Tests;
end Wiki.Tests;
|
Add pre-defined variable in the filters
|
Add pre-defined variable in the filters
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b4924dadc8153bde1a3d73a845649d05976ec373
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data represented by <tt>Data</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Data : in AWA.Storages.Models.Storage_Ref'Class)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Data.Get_Storage);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (AWA.Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder identified by the given id.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
if not Into.Is_Inserted then
Into.Set_Create_Date (Ada.Calendar.Clock);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
Ctx.Commit;
end Save;
-- Load the storage content identified by <b>From</b> in a local file
-- that will be identified by <b>Into</b>.
procedure Load (Service : in Storage_Service;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Models.Store_Local_Ref'Class) is
begin
null;
end Load;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Query.Execute;
Into := Query.Get_Result_Blob;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Into : out AWA.Storages.Models.Store_Local_Ref;
Mode : in Read_Mode := READ;
Expire : in Expire_Type := ONE_DAY) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
Into.Find (DB, Query, Found);
if Found then
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
if Storage.Get_Storage = AWA.Storages.Models.FILE then
Into.Set_Path (String '(Storage.Get_Uri));
return;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into.Get_Path);
Ctx.Commit;
end Load;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Id);
Ctx.Start;
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data represented by <tt>Data</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Data : in AWA.Storages.Models.Storage_Ref'Class)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Data.Get_Storage);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (AWA.Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder identified by the given id.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
if not Into.Is_Inserted then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
Ctx.Commit;
end Save;
-- Load the storage content identified by <b>From</b> in a local file
-- that will be identified by <b>Into</b>.
procedure Load (Service : in Storage_Service;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Models.Store_Local_Ref'Class) is
begin
null;
end Load;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Query.Execute;
Into := Query.Get_Result_Blob;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Into : out AWA.Storages.Models.Store_Local_Ref;
Mode : in Read_Mode := READ;
Expire : in Expire_Type := ONE_DAY) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
Into.Find (DB, Query, Found);
if Found then
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
if Storage.Get_Storage = AWA.Storages.Models.FILE then
Into.Set_Path (String '(Storage.Get_Uri));
return;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into.Get_Path);
Ctx.Commit;
end Load;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Id);
Ctx.Start;
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
Set the storage file owner when creating the storage instance
|
Set the storage file owner when creating the storage instance
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
df65e6c0d361de295ee19bf5f9f5ba437d34648d
|
samples/beans/facebook.adb
|
samples/beans/facebook.adb
|
-----------------------------------------------------------------------
-- facebook - Use Facebook Graph API
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Rest;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with ASF.Sessions;
with ASF.Contexts.Faces;
with ASF.Events.Faces.Actions;
package body Facebook is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook");
type Friend_Field_Type is (FIELD_NAME, FIELD_ID);
type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE,
FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
end case;
end Set_Member;
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field),
Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
when FIELD_FROM =>
Into.From := Value;
when FIELD_MESSAGE =>
Into.Message := Value;
when FIELD_LINK =>
Into.Link := Value;
when FIELD_PICTURE =>
Into.Picture := Value;
when FIELD_ICON =>
Into.Icon := Value;
when FIELD_DESCRIPTION =>
Into.Description := Value;
end case;
end Set_Member;
package Friend_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info,
Element_Type_Access => Friend_Info_Access,
Fields => Friend_Field_Type,
Set_Member => Set_Member);
package Friend_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors,
Element_Mapper => Friend_Mapper);
package Feed_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info,
Element_Type_Access => Feed_Info_Access,
Fields => Feed_Field_Type,
Set_Member => Set_Member);
package Feed_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors,
Element_Mapper => Feed_Mapper);
Friend_Map : aliased Friend_Mapper.Mapper;
Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper;
Feed_Map : aliased Feed_Mapper.Mapper;
Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper;
procedure Get_Friends is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper);
procedure Get_Feeds is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper);
-- ------------------------------
-- Get the access token from the user session.
-- ------------------------------
function Get_Access_Token return String is
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return "";
end if;
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
begin
if not S.Is_Valid then
return "";
end if;
declare
Token : constant Util.Beans.Objects.Object := S.Get_Attribute ("access_token");
begin
if Util.Beans.Objects.Is_Null (Token) then
return "";
else
return Util.Beans.Objects.To_String (Token);
end if;
end;
end;
end Get_Access_Token;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return From.Name;
elsif Name = "id" then
return From.Id;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Feed_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return From.Id;
elsif Name = "name" then
return From.Name;
elsif Name = "from" then
return From.From;
elsif Name = "message" then
return From.Message;
elsif Name = "picture" then
return From.Picture;
elsif Name = "link" then
return From.Link;
elsif Name = "description" then
return From.Description;
elsif Name = "icon" then
return From.Icon;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "hasAccessToken" then
return Util.Beans.Objects.To_Object (False);
end if;
return Friend_List.List_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create a Friend_List bean instance.
-- ------------------------------
function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Friend_List_Bean_Access := new Friend_List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook friends");
Get_Friends ("https://graph.facebook.com/me/friends?access_token="
& Token,
Friend_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Friends_Bean;
-- ------------------------------
-- Build and return a Facebook feed list.
-- ------------------------------
function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Feed_List.List_Bean_Access := new Feed_List.List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook feeds");
Get_Feeds ("https://graph.facebook.com/me/home?access_token="
& Token,
Feed_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Feed_List_Bean;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
overriding
function Get_Value (From : in Facebook_Auth;
Name : in String) return Util.Beans.Objects.Object is
use type ASF.Contexts.Faces.Faces_Context_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if F /= null and Name = "authenticate_url" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (True);
Id : constant String := S.Get_Id;
State : constant String := From.Get_State (Id);
Params : constant String := From.Get_Auth_Params (State, "read_stream");
begin
Log.Info ("OAuth params: {0}", Params);
return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?"
& Params);
end;
elsif F /= null and Name = "isAuthenticated" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (False);
begin
if S.Is_Valid and
then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.To_Object (False);
end if;
end;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Authenticate result from Facebook.
-- ------------------------------
procedure Authenticate (From : in out Facebook_Auth;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
use type Security.OAuth.Clients.Access_Token_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := F.Get_Session;
State : constant String := F.Get_Parameter (Security.OAuth.State);
Code : constant String := F.Get_Parameter (Security.OAuth.Code);
begin
Log.Info ("Auth code {0} for state {1}", Code, State);
if Session.Is_Valid then
if From.Is_Valid_State (Session.Get_Id, State) then
declare
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= From.Request_Access_Token (Code);
begin
if Acc /= null then
Log.Info ("Access token is {0}", Acc.Get_Name);
Session.Set_Attribute ("access_token",
Util.Beans.Objects.To_Object (Acc.Get_Name));
end if;
end;
end if;
end if;
end Authenticate;
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth,
Method => Authenticate,
Name => "authenticate");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Authenticate_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Facebook_Auth)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
begin
Friend_Map.Add_Default_Mapping;
Friend_Vector_Map.Set_Mapping (Friend_Map'Access);
Feed_Map.Add_Mapping ("id", FIELD_ID);
Feed_Map.Add_Mapping ("name", FIELD_NAME);
Feed_Map.Add_Mapping ("message", FIELD_MESSAGE);
Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION);
Feed_Map.Add_Mapping ("from/name", FIELD_FROM);
Feed_Map.Add_Mapping ("picture", FIELD_PICTURE);
Feed_Map.Add_Mapping ("link", FIELD_LINK);
Feed_Map.Add_Mapping ("icon", FIELD_ICON);
Feed_Vector_Map.Set_Mapping (Feed_Map'Access);
end Facebook;
|
-----------------------------------------------------------------------
-- facebook - Use Facebook Graph API
-- Copyright (C) 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.Log.Loggers;
with Util.Http.Rest.Rest_Get_Vector;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with ASF.Sessions;
with ASF.Contexts.Faces;
with ASF.Events.Faces.Actions;
package body Facebook is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook");
type Friend_Field_Type is (FIELD_NAME, FIELD_ID);
type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE,
FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
end case;
end Set_Member;
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field),
Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
when FIELD_FROM =>
Into.From := Value;
when FIELD_MESSAGE =>
Into.Message := Value;
when FIELD_LINK =>
Into.Link := Value;
when FIELD_PICTURE =>
Into.Picture := Value;
when FIELD_ICON =>
Into.Icon := Value;
when FIELD_DESCRIPTION =>
Into.Description := Value;
end case;
end Set_Member;
package Friend_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info,
Element_Type_Access => Friend_Info_Access,
Fields => Friend_Field_Type,
Set_Member => Set_Member);
package Friend_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors,
Element_Mapper => Friend_Mapper);
package Feed_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info,
Element_Type_Access => Feed_Info_Access,
Fields => Feed_Field_Type,
Set_Member => Set_Member);
package Feed_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors,
Element_Mapper => Feed_Mapper);
Friend_Map : aliased Friend_Mapper.Mapper;
Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper;
Feed_Map : aliased Feed_Mapper.Mapper;
Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper;
procedure Get_Friends is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper);
procedure Get_Feeds is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper);
-- ------------------------------
-- Get the access token from the user session.
-- ------------------------------
function Get_Access_Token return String is
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return "";
end if;
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
begin
if not S.Is_Valid then
return "";
end if;
declare
Token : constant Util.Beans.Objects.Object := S.Get_Attribute ("access_token");
begin
if Util.Beans.Objects.Is_Null (Token) then
return "";
else
return Util.Beans.Objects.To_String (Token);
end if;
end;
end;
end Get_Access_Token;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return From.Name;
elsif Name = "id" then
return From.Id;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Feed_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return From.Id;
elsif Name = "name" then
return From.Name;
elsif Name = "from" then
return From.From;
elsif Name = "message" then
return From.Message;
elsif Name = "picture" then
return From.Picture;
elsif Name = "link" then
return From.Link;
elsif Name = "description" then
return From.Description;
elsif Name = "icon" then
return From.Icon;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "hasAccessToken" then
return Util.Beans.Objects.To_Object (False);
end if;
return Friend_List.List_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create a Friend_List bean instance.
-- ------------------------------
function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Friend_List_Bean_Access := new Friend_List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook friends");
Get_Friends ("https://graph.facebook.com/me/friends?access_token="
& Token,
Friend_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Friends_Bean;
-- ------------------------------
-- Build and return a Facebook feed list.
-- ------------------------------
function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Feed_List.List_Bean_Access := new Feed_List.List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook feeds");
Get_Feeds ("https://graph.facebook.com/me/home?access_token="
& Token,
Feed_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Feed_List_Bean;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
overriding
function Get_Value (From : in Facebook_Auth;
Name : in String) return Util.Beans.Objects.Object is
use type ASF.Contexts.Faces.Faces_Context_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if F /= null and Name = "authenticate_url" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (True);
Id : constant String := S.Get_Id;
State : constant String := From.Get_State (Id);
Params : constant String := From.Get_Auth_Params (State, "read_stream");
begin
Log.Info ("OAuth params: {0}", Params);
return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?"
& Params);
end;
elsif F /= null and Name = "isAuthenticated" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (False);
begin
if S.Is_Valid and
then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.To_Object (False);
end if;
end;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Authenticate result from Facebook.
-- ------------------------------
procedure Authenticate (From : in out Facebook_Auth;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
use type Security.OAuth.Clients.Access_Token_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := F.Get_Session;
State : constant String := F.Get_Parameter (Security.OAuth.State);
Code : constant String := F.Get_Parameter (Security.OAuth.Code);
begin
Log.Info ("Auth code {0} for state {1}", Code, State);
if Session.Is_Valid then
if From.Is_Valid_State (Session.Get_Id, State) then
declare
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= From.Request_Access_Token (Code);
begin
if Acc /= null then
Log.Info ("Access token is {0}", Acc.Get_Name);
Session.Set_Attribute ("access_token",
Util.Beans.Objects.To_Object (Acc.Get_Name));
end if;
end;
end if;
end if;
end Authenticate;
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth,
Method => Authenticate,
Name => "authenticate");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Authenticate_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Facebook_Auth)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
begin
Friend_Map.Add_Default_Mapping;
Friend_Vector_Map.Set_Mapping (Friend_Map'Access);
Feed_Map.Add_Mapping ("id", FIELD_ID);
Feed_Map.Add_Mapping ("name", FIELD_NAME);
Feed_Map.Add_Mapping ("message", FIELD_MESSAGE);
Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION);
Feed_Map.Add_Mapping ("from/name", FIELD_FROM);
Feed_Map.Add_Mapping ("picture", FIELD_PICTURE);
Feed_Map.Add_Mapping ("link", FIELD_LINK);
Feed_Map.Add_Mapping ("icon", FIELD_ICON);
Feed_Vector_Map.Set_Mapping (Feed_Map'Access);
end Facebook;
|
Fix compilation of Facebook example
|
Fix compilation of Facebook example
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
3b5b15e485fc44117b1c0916ac7e81b46795b81d
|
src/security-contexts.adb
|
src/security-contexts.adb
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify 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 Ada.Task_Attributes;
with Security.Controllers;
package body Security.Contexts is
package Task_Context is new Ada.Task_Attributes
(Security_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access is
begin
return Context.Principal;
end Get_User_Principal;
-- ------------------------------
-- Get the permission manager.
-- ------------------------------
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Policies.Policy_Manager_Access is
begin
return Context.Manager;
end Get_Permission_Manager;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean) is
use type Security.Policies.Controller_Access;
use type Security.Policies.Policy_Manager_Access;
begin
if Context.Manager = null then
Result := False;
return;
end if;
declare
C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission);
begin
if C = null then
Result := False;
else
-- Result := C.Has_Permission (Context);
Result := False;
end if;
end;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean) is
Index : constant Permissions.Permission_Index
:= Permissions.Get_Permission_Index (Permission);
begin
Security_Context'Class (Context).Has_Permission (Index, Result);
end Has_Permission;
-- ------------------------------
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
-- ------------------------------
overriding
procedure Initialize (Context : in out Security_Context) is
begin
Context.Previous := Task_Context.Value;
Task_Context.Set_Value (Context'Unchecked_Access);
end Initialize;
-- ------------------------------
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
-- ------------------------------
overriding
procedure Finalize (Context : in out Security_Context) is
begin
Task_Context.Set_Value (Context.Previous);
end Finalize;
-- ------------------------------
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
-- ------------------------------
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String) is
begin
Context.Context.Include (Key => Name,
New_Item => Value);
end Add_Context;
-- ------------------------------
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
-- ------------------------------
function Get_Context (Context : in Security_Context;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
raise Invalid_Context;
end if;
end Get_Context;
-- ------------------------------
-- Returns True if a context information was registered under the name <b>Name</b>.
-- ------------------------------
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean is
use type Util.Strings.Maps.Cursor;
begin
return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element;
end Has_Context;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Policies.Policy_Manager_Access;
Principal : in Security.Principal_Access) is
begin
Context.Manager := Manager;
Context.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
-- ------------------------------
function Current return Security_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in String) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
end Security.Contexts;
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify 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 Ada.Task_Attributes;
package body Security.Contexts is
package Task_Context is new Ada.Task_Attributes
(Security_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access is
begin
return Context.Principal;
end Get_User_Principal;
-- ------------------------------
-- Get the permission manager.
-- ------------------------------
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Policies.Policy_Manager_Access is
begin
return Context.Manager;
end Get_Permission_Manager;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean) is
use type Security.Policies.Controller_Access;
use type Security.Policies.Policy_Manager_Access;
begin
if Context.Manager = null then
Result := False;
return;
end if;
declare
C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission);
begin
if C = null then
Result := False;
else
-- Result := C.Has_Permission (Context);
Result := False;
end if;
end;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean) is
Index : constant Permissions.Permission_Index
:= Permissions.Get_Permission_Index (Permission);
begin
Security_Context'Class (Context).Has_Permission (Index, Result);
end Has_Permission;
-- ------------------------------
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
-- ------------------------------
overriding
procedure Initialize (Context : in out Security_Context) is
begin
Context.Previous := Task_Context.Value;
Task_Context.Set_Value (Context'Unchecked_Access);
end Initialize;
-- ------------------------------
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
-- ------------------------------
overriding
procedure Finalize (Context : in out Security_Context) is
begin
Task_Context.Set_Value (Context.Previous);
end Finalize;
-- ------------------------------
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
-- ------------------------------
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String) is
begin
Context.Context.Include (Key => Name,
New_Item => Value);
end Add_Context;
-- ------------------------------
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
-- ------------------------------
function Get_Context (Context : in Security_Context;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
raise Invalid_Context;
end if;
end Get_Context;
-- ------------------------------
-- Returns True if a context information was registered under the name <b>Name</b>.
-- ------------------------------
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean is
use type Util.Strings.Maps.Cursor;
begin
return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element;
end Has_Context;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Policies.Policy_Manager_Access;
Principal : in Security.Principal_Access) is
begin
Context.Manager := Manager;
Context.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
-- ------------------------------
function Current return Security_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in String) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
end Security.Contexts;
|
Remove unused with clause
|
Remove unused with clause
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
145a5780f8eb39e83a9f117f89debbffaf41282a
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Positive'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Positive'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Set_Reader_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
Configure the XML reader for each policy that was registered in the policy manager
|
Configure the XML reader for each policy that was registered in the policy manager
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
0a8dbf74d06a13e056543604ac0848441161d9ef
|
src/util-serialize-io.ads
|
src/util-serialize-io.ads
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- 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.Containers;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers;
with Util.Log.Loggers;
with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is null;
procedure End_Array (Stream : in out Output_Stream) is null;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Parser;
Name : in String);
procedure Start_Array (Handler : in out Parser;
Name : in String);
procedure Finish_Array (Handler : in out Parser;
Name : in String);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access);
-- Dump the mapping tree on the logger using the INFO log level.
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class);
private
-- Implementation limitation: the max number of active mapping nodes
MAX_NODES : constant Positive := 10;
type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access;
procedure Push (Handler : in out Parser);
-- Pop the context and restore the previous context when leaving an element
procedure Pop (Handler : in out Parser);
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
type Element_Context is record
-- The object mapper being process.
Object_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The active mapping nodes.
Active_Nodes : Mapper_Access_Array;
end record;
type Element_Context_Access is access all Element_Context;
package Context_Stack is new Util.Stacks (Element_Type => Element_Context,
Element_Type_Access => Element_Context_Access);
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
Stack : Context_Stack.Stack;
Mapping_Tree : aliased Mappers.Mapper;
Current_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers;
with Util.Log.Loggers;
with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Parser;
Name : in String);
procedure Start_Array (Handler : in out Parser;
Name : in String);
procedure Finish_Array (Handler : in out Parser;
Name : in String);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access);
-- Dump the mapping tree on the logger using the INFO log level.
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class);
private
-- Implementation limitation: the max number of active mapping nodes
MAX_NODES : constant Positive := 10;
type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access;
procedure Push (Handler : in out Parser);
-- Pop the context and restore the previous context when leaving an element
procedure Pop (Handler : in out Parser);
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
type Element_Context is record
-- The object mapper being process.
Object_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The active mapping nodes.
Active_Nodes : Mapper_Access_Array;
end record;
type Element_Context_Access is access all Element_Context;
package Context_Stack is new Util.Stacks (Element_Type => Element_Context,
Element_Type_Access => Element_Context_Access);
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
Stack : Context_Stack.Stack;
Mapping_Tree : aliased Mappers.Mapper;
Current_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
Declare Start_Document, End_Document, Write_Attribute, Write_Entity, Write_Wide_Attribute, Write_Wite_Entity procedures for the output stream
|
Declare Start_Document, End_Document, Write_Attribute, Write_Entity,
Write_Wide_Attribute, Write_Wite_Entity procedures for the output stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
01d7e0c9cd64e5c6732f4ea765a86e5691e96ee1
|
awa/src/awa-events.ads
|
awa/src/awa-events.ads
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- @include Queues.hbm.xml
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- @include Queues.hbm.xml
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
Fix default initialization of a module event
|
Fix default initialization of a module event
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
86f35553c4258a6f02f616c150b94483820f7cdb
|
mat/src/readline/readline.adb
|
mat/src/readline/readline.adb
|
-----------------------------------------------------------------------
-- readline -- A simple readline binding
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.IO_Exceptions;
package body Readline is
pragma Linker_Options ("-lreadline");
function Readline (Prompt : in Interfaces.C.Strings.chars_ptr)
return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Readline, "readline");
procedure Add_History (Line : in Interfaces.C.Strings.chars_ptr);
pragma Import (C, Add_History, "add_history");
-- ------------------------------
-- Print the prompt and a read a line from the terminal.
-- Raise the Ada.IO_Exceptions.End_Error when the EOF is reached.
-- ------------------------------
function Get_Line (Prompt : in String) return String is
use type Interfaces.C.Strings.chars_ptr;
P : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Prompt);
R : Interfaces.C.Strings.chars_ptr;
begin
R := Readline (P);
Interfaces.C.Strings.Free (P);
if R = Interfaces.C.Strings.null_ptr then
raise Ada.IO_Exceptions.End_Error;
end if;
declare
Result : constant String := Interfaces.C.Strings.Value (R);
begin
if Result'Length > 0 then
Add_History (R);
end if;
Interfaces.C.Strings.Free (R);
return Result;
end;
end Get_Line;
end Readline;
|
-----------------------------------------------------------------------
-- readline -- A simple readline binding
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.IO_Exceptions;
package body Readline is
pragma Linker_Options ("-lreadline");
function Readline (Prompt : in Interfaces.C.Strings.chars_ptr)
return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Readline, "readline");
procedure Add_History (Line : in Interfaces.C.Strings.chars_ptr);
pragma Import (C, Add_History, "add_history");
-- ------------------------------
-- Print the prompt and a read a line from the terminal.
-- Raise the Ada.IO_Exceptions.End_Error when the EOF is reached.
-- ------------------------------
function Get_Line (Prompt : in String) return String is
use type Interfaces.C.Strings.chars_ptr;
P : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Prompt);
R : Interfaces.C.Strings.chars_ptr;
begin
R := Readline (P);
Interfaces.C.Strings.Free (P);
if R = Interfaces.C.Strings.Null_Ptr then
raise Ada.IO_Exceptions.End_Error;
end if;
declare
Result : constant String := Interfaces.C.Strings.Value (R);
begin
if Result'Length > 0 then
Add_History (R);
end if;
Interfaces.C.Strings.Free (R);
return Result;
end;
end Get_Line;
end Readline;
|
Fix minor compilation warnings
|
Fix minor compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
71f02eb30ccbb64d55b65d7229fb7d5317ee9986
|
src/babel-stores-local.adb
|
src/babel-stores-local.adb
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local 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 Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Util.Systems.Types;
with Util.Systems.Os;
with Interfaces;
with Babel.Streams.Files;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Babel.Files.File_Size (Size);
exception
when Constraint_Error =>
return Babel.Files.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is
begin
null;
end Open_File;
-- ------------------------------
-- Open a file in the store to read its content with a stream.
-- ------------------------------
overriding
procedure Read_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Buffer : Babel.Files.Buffers.Buffer_Access;
begin
Log.Info ("Read file {0}", Path);
Stream := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
Store.Pool.Get_Buffer (Buffer);
File.Open (Path, Buffer);
end Read_File;
-- ------------------------------
-- Write a file in the store with a stream.
-- ------------------------------
overriding
procedure Write_File (Store : in out Local_Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Util.Systems.Types.mode_t) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Output : Babel.Streams.Refs.Stream_Ref;
begin
Log.Info ("Write file {0}", Path);
Output := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
File.Create (Path, Mode);
Babel.Streams.Refs.Copy (From => Stream,
Into => Output);
end Write_File;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
Log.Error ("Cannot create {0}", Path);
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.File_Type;
use type Babel.Files.Directory_Type;
function Sys_Stat (Path : in System.Address;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "stat");
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
Stat : aliased Util.Systems.Types.Stat_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
use Util.Systems.Types;
use Interfaces.C;
use Babel.Files;
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
Dir : Babel.Files.Directory_Type;
Res : Integer;
Fpath : String (1 .. Path'Length + Name'Length + 3);
begin
Fpath (Path'Range) := Path;
Fpath (Path'Last + 1) := '/';
Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name;
Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL;
Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access);
if (Stat.st_mode and S_IFMT) = S_IFREG then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = Babel.Files.NO_FILE then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size));
Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid));
Babel.Files.Set_Date (File, Stat.st_mtim);
Log.Debug ("Adding {0}", Name);
Into.Add_File (File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Dir := Into.Find (Name);
if Dir = Babel.Files.NO_DIRECTORY then
Dir := Into.Create (Name);
end if;
Into.Add_Directory (Dir);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
-- ------------------------------
-- Set the buffer pool to be used by local store.
-- ------------------------------
procedure Set_Buffers (Store : in out Local_Store_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Store.Pool := Buffers;
end Set_Buffers;
end Babel.Stores.Local;
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local 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 Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Util.Systems.Types;
with Util.Systems.Os;
with Interfaces;
with Babel.Streams.Files;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Babel.Files.File_Size (Size);
exception
when Constraint_Error =>
return Babel.Files.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is
begin
null;
end Open_File;
-- ------------------------------
-- Open a file in the store to read its content with a stream.
-- ------------------------------
overriding
procedure Read_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Buffer : Babel.Files.Buffers.Buffer_Access;
begin
Log.Info ("Read file {0}", Path);
Stream := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
Store.Pool.Get_Buffer (Buffer);
File.Open (Path, Buffer);
end Read_File;
-- ------------------------------
-- Write a file in the store with a stream.
-- ------------------------------
overriding
procedure Write_File (Store : in out Local_Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Babel.Files.File_Mode) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Output : Babel.Streams.Refs.Stream_Ref;
begin
Log.Info ("Write file {0}", Path);
Output := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
File.Create (Path, Interfaces.C.unsigned (Mode));
Babel.Streams.Refs.Copy (From => Stream,
Into => Output);
end Write_File;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
Log.Error ("Cannot create {0}", Path);
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.File_Type;
use type Babel.Files.Directory_Type;
function Sys_Stat (Path : in System.Address;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "stat");
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
Stat : aliased Util.Systems.Types.Stat_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
use Util.Systems.Types;
use Interfaces.C;
use Babel.Files;
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
Dir : Babel.Files.Directory_Type;
Res : Integer;
Fpath : String (1 .. Path'Length + Name'Length + 3);
begin
Fpath (Path'Range) := Path;
Fpath (Path'Last + 1) := '/';
Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name;
Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL;
Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access);
if (Stat.st_mode and S_IFMT) = S_IFREG then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = Babel.Files.NO_FILE then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size));
Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid));
Babel.Files.Set_Date (File, Stat.st_mtim);
Log.Debug ("Adding {0}", Name);
Into.Add_File (File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Dir := Into.Find (Name);
if Dir = Babel.Files.NO_DIRECTORY then
Dir := Into.Create (Name);
end if;
Into.Add_Directory (Dir);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
-- ------------------------------
-- Set the buffer pool to be used by local store.
-- ------------------------------
procedure Set_Buffers (Store : in out Local_Store_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Store.Pool := Buffers;
end Set_Buffers;
end Babel.Stores.Local;
|
Change Write_File to use the Babel.Files.File_Mode type
|
Change Write_File to use the Babel.Files.File_Mode type
|
Ada
|
apache-2.0
|
stcarrez/babel
|
bf57b472e3d7be4114683b99540cd5ac6d59c0c0
|
src/natools-smaz_generic.adb
|
src/natools-smaz_generic.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Generic is
use type Ada.Streams.Stream_Element_Offset;
procedure Find_Entry
(Dict : in Dictionary;
Template : in String;
Code : out Dictionary_Code;
Length : out Natural);
-- Try to find the longest entry in Dict that is a prefix of Template,
-- setting Length to 0 when no such entry exists.
function Verbatim_Size
(Dict : in Dictionary;
Length : in Positive)
return Ada.Streams.Stream_Element_Count
is (Verbatim_Size (Length, Dict.Last_Code, Dict.Variable_Length_Verbatim));
-- Wrapper around the formal Verbatim_Size
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Find_Entry
(Dict : in Dictionary;
Template : in String;
Code : out Dictionary_Code;
Length : out Natural)
is
N : Natural;
Is_Valid : Boolean;
begin
Length := 0;
for Last in reverse Template'Range loop
Is_Valid := False;
N := Dict.Hash (Template (Template'First .. Last));
To_Code :
begin
Code := Dictionary_Code'Val (N);
if Is_Valid_Code (Dict, Code) then
Is_Valid := True;
end if;
exception
when Constraint_Error => null;
end To_Code;
if Is_Valid
and then Template (Template'First .. Last)
= Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First)
.. Code_Last (Dict.Offsets, Code, Dict.Values'Last))
then
Length := 1 + Last - Template'First;
return;
end if;
end loop;
end Find_Entry;
----------------------
-- Public Interface --
----------------------
function Compressed_Upper_Bound
(Dict : in Dictionary;
Input : in String)
return Ada.Streams.Stream_Element_Count is
begin
return Verbatim_Size
(Input'Length, Dict.Last_Code, Dict.Variable_Length_Verbatim);
end Compressed_Upper_Bound;
procedure Compress
(Dict : in Dictionary;
Input : in String;
Output_Buffer : out Ada.Streams.Stream_Element_Array;
Output_Last : out Ada.Streams.Stream_Element_Offset)
is
procedure Find_Current_Entry;
Input_Index : Positive := Input'First;
Length : Natural;
Code : Dictionary_Code;
Output_Index : Ada.Streams.Stream_Element_Offset;
procedure Find_Current_Entry is
begin
Find_Entry
(Dict,
Input (Input_Index
.. Natural'Min (Input_Index + Dict.Max_Word_Length - 1,
Input'Last)),
Code,
Length);
end Find_Current_Entry;
Previous_Verbatim_Beginning : Natural := 0;
Previous_Verbatim_Index : Ada.Streams.Stream_Element_Offset := 0;
begin
Output_Index := Output_Buffer'First;
Find_Current_Entry;
Main_Loop :
while Input_Index in Input'Range loop
Data_In_Dict :
while Length > 0 loop
Write_Code (Output_Buffer, Output_Index, Code);
Input_Index := Input_Index + Length;
exit Main_Loop when Input_Index not in Input'Range;
Find_Current_Entry;
end loop Data_In_Dict;
Verbatim_Block :
declare
Beginning : Positive := Input_Index;
Verbatim_Length : Natural;
begin
Verbatim_Scan :
while Length = 0 and Input_Index in Input'Range loop
Input_Index := Input_Index + 1;
Find_Current_Entry;
end loop Verbatim_Scan;
Verbatim_Length := Input_Index - Beginning;
if Previous_Verbatim_Beginning > 0
and then Output_Index + Verbatim_Size (Dict, Verbatim_Length)
>= Previous_Verbatim_Index + Verbatim_Size
(Dict, Input_Index - Previous_Verbatim_Beginning)
then
Beginning := Previous_Verbatim_Beginning;
Output_Index := Previous_Verbatim_Index;
Verbatim_Length := Input_Index - Beginning;
else
Previous_Verbatim_Beginning := Beginning;
Previous_Verbatim_Index := Output_Index;
end if;
Write_Verbatim
(Output_Buffer, Output_Index,
Input (Beginning .. Input_Index - 1),
Dict.Last_Code, Dict.Variable_Length_Verbatim);
end Verbatim_Block;
end loop Main_Loop;
Output_Last := Output_Index - 1;
end Compress;
function Compress (Dict : in Dictionary; Input : in String)
return Ada.Streams.Stream_Element_Array
is
Result : Ada.Streams.Stream_Element_Array
(1 .. Compressed_Upper_Bound (Dict, Input));
Last : Ada.Streams.Stream_Element_Offset;
begin
Compress (Dict, Input, Result, Last);
return Result (Result'First .. Last);
end Compress;
function Decompressed_Length
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array)
return Natural
is
Result : Natural := 0;
Input_Index : Ada.Streams.Stream_Element_Offset := Input'First;
Code : Dictionary_Code;
Verbatim_Length : Natural;
begin
while Input_Index in Input'Range loop
Read_Code
(Input, Input_Index,
Code, Verbatim_Length,
Dict.Last_Code, Dict.Variable_Length_Verbatim);
if Verbatim_Length > 0 then
Skip_Verbatim (Input, Input_Index, Verbatim_Length);
Result := Result + Verbatim_Length;
else
Result := Result + Dict_Entry_Length (Dict, Code);
end if;
end loop;
return Result;
end Decompressed_Length;
procedure Decompress
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array;
Output_Buffer : out String;
Output_Last : out Natural)
is
Input_Index : Ada.Streams.Stream_Element_Offset := Input'First;
Code : Dictionary_Code;
Verbatim_Length : Natural;
begin
Output_Last := Output_Buffer'First - 1;
while Input_Index in Input'Range loop
Read_Code
(Input, Input_Index,
Code, Verbatim_Length,
Dict.Last_Code, Dict.Variable_Length_Verbatim);
if Verbatim_Length > 0 then
Read_Verbatim
(Input, Input_Index,
Output_Buffer
(Output_Last + 1 .. Output_Last + Verbatim_Length));
Output_Last := Output_Last + Verbatim_Length;
else
declare
Decoded : constant String := Dict_Entry (Dict, Code);
begin
Output_Buffer (Output_Last + 1 .. Output_Last + Decoded'Length)
:= Decoded;
Output_Last := Output_Last + Decoded'Length;
end;
end if;
end loop;
end Decompress;
function Decompress
(Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array)
return String
is
Result : String (1 .. Decompressed_Length (Dict, Input));
Last : Natural;
begin
Decompress (Dict, Input, Result, Last);
pragma Assert (Last = Result'Last);
return Result;
end Decompress;
end Natools.Smaz_Generic;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Generic is
use type Ada.Streams.Stream_Element_Offset;
procedure Find_Entry
(Dict : in Dictionary;
Template : in String;
Code : out Dictionary_Code;
Length : out Natural);
-- Try to find the longest entry in Dict that is a prefix of Template,
-- setting Length to 0 when no such entry exists.
function Verbatim_Size
(Dict : in Dictionary;
Length : in Positive)
return Ada.Streams.Stream_Element_Count
is (Verbatim_Size (Length, Dict.Last_Code, Dict.Variable_Length_Verbatim));
-- Wrapper around the formal Verbatim_Size
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Find_Entry
(Dict : in Dictionary;
Template : in String;
Code : out Dictionary_Code;
Length : out Natural)
is
N : Natural;
Is_Valid : Boolean;
begin
Length := 0;
for Last in reverse Template'Range loop
Is_Valid := False;
N := Dict.Hash (Template (Template'First .. Last));
To_Code :
begin
Code := Dictionary_Code'Val (N);
if Is_Valid_Code (Dict, Code) then
Is_Valid := True;
end if;
exception
when Constraint_Error => null;
end To_Code;
if Is_Valid
and then Template (Template'First .. Last)
= Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First)
.. Code_Last (Dict.Offsets, Code, Dict.Values'Last))
then
Length := 1 + Last - Template'First;
return;
end if;
end loop;
end Find_Entry;
----------------------
-- Public Interface --
----------------------
function Compressed_Upper_Bound
(Dict : in Dictionary;
Input : in String)
return Ada.Streams.Stream_Element_Count is
begin
return Verbatim_Size
(Input'Length, Dict.Last_Code, Dict.Variable_Length_Verbatim);
end Compressed_Upper_Bound;
procedure Compress
(Dict : in Dictionary;
Input : in String;
Output_Buffer : out Ada.Streams.Stream_Element_Array;
Output_Last : out Ada.Streams.Stream_Element_Offset)
is
procedure Find_Current_Entry;
Input_Index : Positive := Input'First;
Length : Natural;
Code : Dictionary_Code;
Output_Index : Ada.Streams.Stream_Element_Offset;
procedure Find_Current_Entry is
begin
Find_Entry
(Dict,
Input (Input_Index
.. Natural'Min (Input_Index + Dict.Max_Word_Length - 1,
Input'Last)),
Code,
Length);
end Find_Current_Entry;
Previous_Verbatim_Beginning : Natural := 0;
Previous_Verbatim_Index : Ada.Streams.Stream_Element_Offset := 0;
begin
Output_Index := Output_Buffer'First;
Find_Current_Entry;
Main_Loop :
while Input_Index in Input'Range loop
Data_In_Dict :
while Length > 0 loop
Write_Code (Output_Buffer, Output_Index, Code);
Input_Index := Input_Index + Length;
exit Main_Loop when Input_Index not in Input'Range;
Find_Current_Entry;
end loop Data_In_Dict;
Verbatim_Block :
declare
Beginning : Positive := Input_Index;
Verbatim_Length : Natural;
begin
Verbatim_Scan :
while Length = 0 and Input_Index in Input'Range loop
Input_Index := Input_Index + 1;
Find_Current_Entry;
end loop Verbatim_Scan;
Verbatim_Length := Input_Index - Beginning;
if Previous_Verbatim_Beginning > 0
and then Output_Index + Verbatim_Size (Dict, Verbatim_Length)
>= Previous_Verbatim_Index + Verbatim_Size
(Dict, Input_Index - Previous_Verbatim_Beginning)
then
Beginning := Previous_Verbatim_Beginning;
Output_Index := Previous_Verbatim_Index;
Verbatim_Length := Input_Index - Beginning;
else
Previous_Verbatim_Beginning := Beginning;
Previous_Verbatim_Index := Output_Index;
end if;
Write_Verbatim
(Output_Buffer, Output_Index,
Input (Beginning .. Input_Index - 1),
Dict.Last_Code, Dict.Variable_Length_Verbatim);
end Verbatim_Block;
end loop Main_Loop;
Output_Last := Output_Index - 1;
end Compress;
function Compress (Dict : in Dictionary; Input : in String)
return Ada.Streams.Stream_Element_Array
is
Result : Ada.Streams.Stream_Element_Array
(1 .. Compressed_Upper_Bound (Dict, Input));
Last : Ada.Streams.Stream_Element_Offset;
begin
Compress (Dict, Input, Result, Last);
return Result (Result'First .. Last);
end Compress;
function Decompressed_Length
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array)
return Natural
is
Result : Natural := 0;
Input_Index : Ada.Streams.Stream_Element_Offset := Input'First;
Code : Dictionary_Code;
Verbatim_Length : Natural;
begin
while Input_Index in Input'Range loop
Read_Code
(Input, Input_Index,
Code, Verbatim_Length,
Dict.Last_Code, Dict.Variable_Length_Verbatim);
if Verbatim_Length > 0 then
Skip_Verbatim (Input, Input_Index, Verbatim_Length);
Result := Result + Verbatim_Length;
else
exit when not Is_Valid_Code (Dict, Code);
Result := Result + Dict_Entry_Length (Dict, Code);
end if;
end loop;
return Result;
end Decompressed_Length;
procedure Decompress
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array;
Output_Buffer : out String;
Output_Last : out Natural)
is
Input_Index : Ada.Streams.Stream_Element_Offset := Input'First;
Code : Dictionary_Code;
Verbatim_Length : Natural;
begin
Output_Last := Output_Buffer'First - 1;
while Input_Index in Input'Range loop
Read_Code
(Input, Input_Index,
Code, Verbatim_Length,
Dict.Last_Code, Dict.Variable_Length_Verbatim);
if Verbatim_Length > 0 then
Read_Verbatim
(Input, Input_Index,
Output_Buffer
(Output_Last + 1 .. Output_Last + Verbatim_Length));
Output_Last := Output_Last + Verbatim_Length;
else
exit when not Is_Valid_Code (Dict, Code);
declare
Decoded : constant String := Dict_Entry (Dict, Code);
begin
Output_Buffer (Output_Last + 1 .. Output_Last + Decoded'Length)
:= Decoded;
Output_Last := Output_Last + Decoded'Length;
end;
end if;
end loop;
end Decompress;
function Decompress
(Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array)
return String
is
Result : String (1 .. Decompressed_Length (Dict, Input));
Last : Natural;
begin
Decompress (Dict, Input, Result, Last);
pragma Assert (Last = Result'Last);
return Result;
end Decompress;
end Natools.Smaz_Generic;
|
update semantics of Read_Code to signal end-of-input
|
smaz_generic: update semantics of Read_Code to signal end-of-input
|
Ada
|
isc
|
faelys/natools
|
c470a93de8be38b804a979f107c253469f6beab9
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map) is
begin
if Filter.Next /= null then
Filter.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Next /= null then
Filter.Push_Node (Document, Tag, Attributes);
else
Wiki.Nodes.Append (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type) is
begin
if Filter.Next /= null then
Filter.Pop_Node (Document, Tag);
else
Wiki.Nodes.Append (Document, Tag);
end if;
end Pop_Node;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map) is
begin
if Filter.Next /= null then
Filter.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Next /= null then
Filter.Push_Node (Document, Tag, Attributes);
else
Wiki.Nodes.Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type) is
begin
if Filter.Next /= null then
Filter.Pop_Node (Document, Tag);
else
Wiki.Nodes.Pop_Node (Document, Tag);
end if;
end Pop_Node;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
end Wiki.Filters;
|
Use Push_Node and Pop_Node for the HTML tag management
|
Use Push_Node and Pop_Node for the HTML tag management
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8144e4825e3161118b6f2265e01fc16446184ca7
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Document.Add_Header (Header, Level);
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Filter_Type) is
begin
Document.Document.Add_Line_Break;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Filter_Type) is
begin
Document.Document.Add_Paragraph;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type) is
begin
Document.Document.Add_Horizontal_Rule;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
-- ------------------------------
-- Set the document reader.
-- ------------------------------
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access) is
begin
Filter.Document := Document;
end Set_Document;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Document.Add_Header (Header, Level);
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Filter_Type) is
begin
Document.Document.Add_Line_Break;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Filter_Type) is
begin
Document.Document.Add_Paragraph;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type) is
begin
Document.Document.Add_Horizontal_Rule;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
-- ------------------------------
-- Set the document reader.
-- ------------------------------
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access) is
begin
Filter.Document := Document;
end Set_Document;
end Wiki.Filters;
|
Implement the Add_Node procedure
|
Implement the Add_Node procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
81ae2fa64cd111e4e5e7b2d066fb6eea18564473
|
src/wiki-helpers.adb
|
src/wiki-helpers.adb
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the character is a line terminator.
-- ------------------------------
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wiki.Strings.WString) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is
S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
-- ------------------------------
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural) is
Pos : Natural;
Last : Natural;
begin
if Dimension = "original" then
Width := Natural'Last;
Height := Natural'Last;
elsif Dimension = "default" or Dimension = "upright" then
Width := 800;
Height := 0;
else
Pos := Wiki.Strings.Index (Dimension, "x");
Last := Wiki.Strings.Index (Dimension, "px");
if Pos > Dimension'First and Last + 1 /= Pos then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1));
elsif Last > 0 then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1));
else
Width := 0;
end if;
if Pos < Dimension'Last then
Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1));
else
Height := 0;
end if;
end if;
exception
when Constraint_Error =>
Width := 0;
Height := 0;
end Get_Sizes;
end Wiki.Helpers;
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
with Ada.Wide_Wide_Characters.Unicode;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the character is a punctuation character.
-- ------------------------------
function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Unicode.Is_Punctuation (C);
end Is_Punctuation;
-- ------------------------------
-- Returns True if the character is a line terminator.
-- ------------------------------
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wiki.Strings.WString) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is
S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
-- ------------------------------
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural) is
Pos : Natural;
Last : Natural;
begin
if Dimension = "original" then
Width := Natural'Last;
Height := Natural'Last;
elsif Dimension = "default" or Dimension = "upright" then
Width := 800;
Height := 0;
else
Pos := Wiki.Strings.Index (Dimension, "x");
Last := Wiki.Strings.Index (Dimension, "px");
if Pos > Dimension'First and Last + 1 /= Pos then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1));
elsif Last > 0 then
Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1));
else
Width := 0;
end if;
if Pos < Dimension'Last then
Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1));
else
Height := 0;
end if;
end if;
exception
when Constraint_Error =>
Width := 0;
Height := 0;
end Get_Sizes;
-- ------------------------------
-- Find the position of the first non space character in the text starting at the
-- given position. Returns Text'Last + 1 if the text only contains spaces.
-- ------------------------------
function Skip_Spaces (Text : in Wiki.Strings.Wstring;
From : in Positive) return Positive is
Pos : Positive := From;
begin
while Pos <= Text'Last and then Is_Space (Text (Pos)) loop
Pos := Pos + 1;
end loop;
return Pos;
end Skip_Spaces;
end Wiki.Helpers;
|
Add Skip_Spaces function
|
Add Skip_Spaces function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ba35aa4a287365a7fd117315e2ff289f1c7839ee
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management 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.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management 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.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
Save the allow comment flag on the post
|
Save the allow comment flag on the post
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
d1cd462b51004151346f5368f518ad085f71dfeb
|
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, 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 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
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 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;
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
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
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 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);
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);
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;
|
Remove 'table' parameter from queries because it is not needed anymore
|
Remove 'table' parameter from queries because it is not needed anymore
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
010bee4f65e99b1e0f9104a567675b1894117c2b
|
awa/plugins/awa-votes/src/awa-votes-modules.adb
|
awa/plugins/awa-votes/src/awa-votes-modules.adb
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Permissions;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Votes.Beans;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Votes.Models;
with ADO.SQL;
with ADO.Sessions;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Votes.Modules is
use AWA.Services;
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module");
package Register is new AWA.Modules.Beans (Module => Vote_Module,
Module_Access => Vote_Module_Access);
-- ------------------------------
-- Initialize the votes module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the votes module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Votes.Beans.Votes_Bean",
Handler => AWA.Votes.Beans.Create_Vote_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the votes module.
-- ------------------------------
function Get_Vote_Module return Vote_Module_Access is
function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME);
begin
return Get;
end Get_Vote_Module;
-- ------------------------------
-- Vote for the given element and return the total vote for that element.
-- ------------------------------
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer) is
pragma Unreferenced (Model);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Rating : AWA.Votes.Models.Rating_Ref;
Vote : AWA.Votes.Models.Vote_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Log.Info ("User {0} votes for {1} rating {2}",
ADO.Identifier'Image (User.Get_Id), Entity_Type & ADO.Identifier'Image (Id),
Integer'Image (Value));
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Check that the user has the vote permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
-- Get the vote associated with the object for the user.
Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id");
Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type "
& "and o.user_id = :user_id");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Query.Bind_Param ("user_id", User.Get_Id);
Vote.Find (DB, Query, Found);
if not Found then
Query.Clear;
-- Get the rating associated with the object.
Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Rating.Find (DB, Query, Found);
-- Create it if it does not exist.
if not Found then
Rating.Set_For_Entity_Id (Id);
Rating.Set_For_Entity_Type (Kind);
Rating.Set_Rating (Value);
Rating.Set_Vote_Count (1);
else
Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1);
Rating.Set_Rating (Value + Rating.Get_Rating);
end if;
Rating.Save (DB);
Vote.Set_User (User);
Vote.Set_Entity (Rating);
else
Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity);
Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating);
Rating.Save (DB);
end if;
Vote.Set_Rating (Value);
Vote.Save (DB);
-- Return the total rating for the element.
Total := Rating.Get_Rating;
Ctx.Commit;
end Vote_For;
end AWA.Votes.Modules;
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Permissions;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Votes.Beans;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Votes.Models;
with ADO.SQL;
with ADO.Sessions;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Votes.Modules is
use AWA.Services;
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module");
package Register is new AWA.Modules.Beans (Module => Vote_Module,
Module_Access => Vote_Module_Access);
-- ------------------------------
-- Initialize the votes module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the votes module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Votes.Beans.Votes_Bean",
Handler => AWA.Votes.Beans.Create_Vote_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the votes module.
-- ------------------------------
function Get_Vote_Module return Vote_Module_Access is
function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME);
begin
return Get;
end Get_Vote_Module;
-- ------------------------------
-- Vote for the given element and return the total vote for that element.
-- ------------------------------
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer) is
pragma Unreferenced (Model);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Rating : AWA.Votes.Models.Rating_Ref;
Vote : AWA.Votes.Models.Vote_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
begin
Log.Info ("User {0} votes for {1} rating {2}",
ADO.Identifier'Image (User.Get_Id), Ident,
Integer'Image (Value));
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Check that the user has the vote permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
-- Get the vote associated with the object for the user.
Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id");
Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type "
& "and o.user_id = :user_id");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Query.Bind_Param ("user_id", User.Get_Id);
Vote.Find (DB, Query, Found);
if not Found then
-- If the rating is 0, do not create any vote.
if Value = 0 then
return;
end if;
Query.Clear;
-- Get the rating associated with the object.
Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Rating.Find (DB, Query, Found);
-- Create it if it does not exist.
if not Found then
Log.Info ("Creating rating for {0}", Ident);
Rating.Set_For_Entity_Id (Id);
Rating.Set_For_Entity_Type (Kind);
Rating.Set_Rating (Value);
Rating.Set_Vote_Count (1);
else
Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1);
Rating.Set_Rating (Value + Rating.Get_Rating);
end if;
Rating.Save (DB);
Vote.Set_User (User);
Vote.Set_Entity (Rating);
else
Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity);
Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating);
Rating.Save (DB);
end if;
Vote.Set_Rating (Value);
Vote.Save (DB);
-- Return the total rating for the element.
Total := Rating.Get_Rating;
Ctx.Commit;
end Vote_For;
end AWA.Votes.Modules;
|
Add a log when the rating is created
|
Add a log when the rating is created
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
952e6bb4219cf1d26ebf87b1a4eaa03a7a906c14
|
src/util-streams-sockets.ads
|
src/util-streams-sockets.ads
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013, 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 GNAT.Sockets;
-- == Sockets ==
-- The <b>Util.Streams.Sockets</b> package defines a socket stream.
package Util.Streams.Sockets is
-- -----------------------
-- Socket stream
-- -----------------------
-- The <b>Socket_Stream</b> is an output/input stream that reads or writes
-- to or from a socket.
type Socket_Stream is limited new Output_Stream and Input_Stream with private;
-- Initialize the socket stream.
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type);
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type);
-- Close the socket stream.
overriding
procedure Close (Stream : in out Socket_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Socket_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Sock : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Socket_Stream);
end Util.Streams.Sockets;
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013, 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 GNAT.Sockets;
-- == Sockets ==
-- The <b>Util.Streams.Sockets</b> package defines a socket stream.
package Util.Streams.Sockets is
-- -----------------------
-- Socket stream
-- -----------------------
-- The <b>Socket_Stream</b> is an output/input stream that reads or writes
-- to or from a socket.
type Socket_Stream is limited new Output_Stream and Input_Stream with private;
-- Initialize the socket stream.
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type);
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type);
-- Close the socket stream.
overriding
procedure Close (Stream : in out Socket_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Socket_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Sock : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Socket_Stream);
end Util.Streams.Sockets;
|
Remove unused use Ada.Streams clause reported by GNAT 2018
|
Remove unused use Ada.Streams clause reported by GNAT 2018
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d4e951ba2eabdfff7a95a9d654151975a3563fbd
|
src/wiki-writers.ads
|
src/wiki-writers.ads
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- 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.Strings.Wide_Wide_Unbounded;
with Wiki.Parsers;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
package Wiki.Writers is
use Ada.Strings.Wide_Wide_Unbounded;
type Writer_Type is limited interface;
type Writer_Type_Access is access all Writer_Type'Class;
procedure Write (Writer : in out Writer_Type;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Writer : in out Writer_Type;
Char : in Wide_Wide_Character) is abstract;
procedure Write (Writer : in out Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
type Html_Writer_Type is limited interface and Writer_Type;
type Html_Writer_Type_Access is access all Html_Writer_Type'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_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) 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_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
procedure foo;
end Wiki.Writers;
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- 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.Strings.Wide_Wide_Unbounded;
with Wiki.Parsers;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
package Wiki.Writers is
use Ada.Strings.Wide_Wide_Unbounded;
type Writer_Type is limited interface;
type Writer_Type_Access is access all Writer_Type'Class;
procedure Write (Writer : in out Writer_Type;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Writer : in out Writer_Type;
Char : in Wide_Wide_Character) is abstract;
procedure Write (Writer : in out Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
type Html_Writer_Type is limited interface and Writer_Type;
type Html_Writer_Type_Access is access all Html_Writer_Type'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_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) 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_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) 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_writer_Type'Class;
Name : in String;
Content : in String);
end Wiki.Writers;
|
Declare the Write_Attribute procedure
|
Declare the Write_Attribute procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9566bde1e704eba255344ba90d8fe9a7961c39cf
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "60";
copyright_years : constant String := "2015-2020";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
spkg_nls : constant String := "nls";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-8.0";
default_lua : constant String := "5.3";
default_perl : constant String := "5.30";
default_pgsql : constant String := "12";
default_php : constant String := "7.4";
default_python3 : constant String := "3.8";
default_ruby : constant String := "2.7";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_binutils : constant String := "binutils:ravensys";
default_compiler : constant String := "gcc9";
previous_default : constant String := "gcc9";
compiler_version : constant String := "9.3.0";
previous_compiler : constant String := "9.2.0";
binutils_version : constant String := "2.35.1";
previous_binutils : constant String := "2.34";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
task_stack_limit : constant := 10_000_000;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 64;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/ravensw";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "61";
copyright_years : constant String := "2015-2020";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
spkg_nls : constant String := "nls";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-8.0";
default_lua : constant String := "5.3";
default_perl : constant String := "5.30";
default_pgsql : constant String := "12";
default_php : constant String := "7.4";
default_python3 : constant String := "3.8";
default_ruby : constant String := "2.7";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_binutils : constant String := "binutils:ravensys";
default_compiler : constant String := "gcc9";
previous_default : constant String := "gcc9";
compiler_version : constant String := "9.3.0";
previous_compiler : constant String := "9.2.0";
binutils_version : constant String := "2.35.1";
previous_binutils : constant String := "2.34";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
task_stack_limit : constant := 10_000_000;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 64;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/ravensw";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version for imminent release
|
Bump version for imminent release
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
352614863c8c91055e54ecebffd42a8c32368d94
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- Initialize the authentication realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
null;
end Associate;
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
null;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Add some comments
|
Add some comments
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
82823eb824b504d29484ae9dbe84a1cfbb17d3e0
|
src/util-streams-buffered.ads
|
src/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered streams Stream utilities
-- Copyright (C) 2010, 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.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
-- -----------------------
-- Buffered stream
-- -----------------------
-- The <b>Buffered_Stream</b> is an output/input stream which uses
-- an intermediate buffer. It can be configured to read or write to
-- another stream that it will read or write using the buffer.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the buffered stream.
type Buffered_Stream is limited new Output_Stream and Input_Stream with private;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Buffered_Stream;
Output : in Output_Stream_Access;
Input : in Input_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Buffered_Stream;
Size : in Positive);
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Buffered_Stream;
Content : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Buffered_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access;
-- Write a raw character on the stream.
procedure Write (Stream : in out Buffered_Stream;
Char : in Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Buffered_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Buffered_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Buffered_Stream) return Natural;
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Buffered_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Buffered_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Buffered_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Buffered_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Buffered_Stream) return Boolean;
private
use Ada.Streams;
type Buffered_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
No_Flush : Boolean := False;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Buffered_Stream);
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered streams Stream utilities
-- Copyright (C) 2010, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
-- -----------------------
-- Buffered stream
-- -----------------------
-- The <b>Buffered_Stream</b> is an output/input stream which uses
-- an intermediate buffer. It can be configured to read or write to
-- another stream that it will read or write using the buffer.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the buffered stream.
type Buffered_Stream is limited new Output_Stream and Input_Stream with private;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Buffered_Stream;
Output : in Output_Stream_Access;
Input : in Input_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Buffered_Stream;
Size : in Positive);
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Buffered_Stream;
Content : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Buffered_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access;
-- Write a raw character on the stream.
procedure Write (Stream : in out Buffered_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Buffered_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Buffered_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Buffered_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Buffered_Stream) return Natural;
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Buffered_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Buffered_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Buffered_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Buffered_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Buffered_Stream) return Boolean;
private
use Ada.Streams;
type Buffered_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
No_Flush : Boolean := False;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Buffered_Stream);
end Util.Streams.Buffered;
|
Declare the Write_Wide procedure to write a wide wide character (use a different name to avoid problems writing single literal characters)
|
Declare the Write_Wide procedure to write a wide wide character
(use a different name to avoid problems writing single literal characters)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
579c783753aec571c8f1d407c2e6528e9cc67439
|
testcases/driver_connections/mysql/connect.adb
|
testcases/driver_connections/mysql/connect.adb
|
-- Used for all testcases for MySQL driver
-- Modify connection parameters as necessary
with AdaBase.Driver.Base.MySQL;
package body Connect is
procedure connect_database is
begin
DR.basic_connect (database => "adabase_examples",
username => "root",
password => "",
hostname => "localhost",
port => 3306);
end connect_database;
end Connect;
|
-- Used for all testcases for MySQL driver
-- Modify connection parameters as necessary
package body Connect is
procedure connect_database is
begin
DR.basic_connect (database => "adabase_examples",
username => "root",
password => "",
hostname => "localhost",
port => 3306);
end connect_database;
end Connect;
|
Remove unnecessary WITH from mysql connection
|
Remove unnecessary WITH from mysql connection
|
Ada
|
isc
|
jrmarino/AdaBase
|
00b3dd24a9b5dabceb60da9238f05d280f4866ae
|
src/asf-applications-messages-factory.adb
|
src/asf-applications-messages-factory.adb
|
-----------------------------------------------------------------------
-- applications.messages-factory -- Application Message Factory
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with Util.Properties.Bundles;
with Util.Beans.Objects;
with ASF.Locales;
with ASF.Applications.Main;
package body ASF.Applications.Messages.Factory is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory");
-- ------------------------------
-- Get a localized message. The message identifier is composed of a resource bundle name
-- prefix and a bundle key. The prefix and key are separated by the first '.'.
-- If the message identifier does not contain any prefix, the default bundle is "messages".
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String) return String is
Pos : constant Natural := Util.Strings.Index (Message_Id, '.');
App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application;
Bundle : ASF.Locales.Bundle;
begin
if Pos > 0 then
App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1),
Locale => "en",
Bundle => Bundle);
return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last),
Message_Id (Pos + 1 .. Message_Id'Last));
else
App.Load_Bundle (Name => "messages",
Locale => "en",
Bundle => Bundle);
return Bundle.Get (Message_Id, Message_Id);
end if;
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E));
return Message_Id;
end Get_Message;
-- ------------------------------
-- Build a localized message.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) return Message is
Msg : constant String := Get_Message (Context, Message_Id);
Result : Message;
begin
Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg);
Result.Kind := Severity;
return Result;
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with one argument.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) return Message is
Args : ASF.Utils.Object_Array (1 .. 1);
begin
Args (1) := Util.Beans.Objects.To_Object (Param1);
return Get_Message (Context, Message_Id, Args, Severity);
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with two argument.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Param2 : in String;
Severity : in Messages.Severity := ERROR) return Message is
Args : ASF.Utils.Object_Array (1 .. 2);
begin
Args (1) := Util.Beans.Objects.To_Object (Param1);
Args (2) := Util.Beans.Objects.To_Object (Param2);
return Get_Message (Context, Message_Id, Args, Severity);
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with some arguments.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Args : in ASF.Utils.Object_Array;
Severity : in Messages.Severity := ERROR) return Message is
Msg : constant String := Get_Message (Context, Message_Id);
Result : Message;
begin
Result.Kind := Severity;
ASF.Utils.Formats.Format (Msg, Args, Result.Summary);
return Result;
end Get_Message;
-- ------------------------------
-- Add a localized global message in the faces context.
-- ------------------------------
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) is
Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity);
begin
Context.Add_Message (Client_Id => "", Message => Msg);
end Add_Message;
-- ------------------------------
-- Add a localized global message in the faces context.
-- ------------------------------
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) is
Msg : constant Message := Get_Message (Context, Message_Id, Severity);
begin
Context.Add_Message (Client_Id => "", Message => Msg);
end Add_Message;
-- ------------------------------
-- Add a localized global message in the current faces context.
-- ------------------------------
procedure Add_Message (Message_Id : in String;
Severity : in Messages.Severity := ERROR) is
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
Add_Message (Context.all, Message_Id, Severity);
end Add_Message;
end ASF.Applications.Messages.Factory;
|
-----------------------------------------------------------------------
-- applications.messages-factory -- Application Message Factory
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with Util.Properties.Bundles;
with Util.Beans.Objects;
with Util.Locales;
with ASF.Locales;
with ASF.Applications.Main;
package body ASF.Applications.Messages.Factory is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory");
-- ------------------------------
-- Get a localized message. The message identifier is composed of a resource bundle name
-- prefix and a bundle key. The prefix and key are separated by the first '.'.
-- If the message identifier does not contain any prefix, the default bundle is "messages".
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String) return String is
Pos : constant Natural := Util.Strings.Index (Message_Id, '.');
Locale : constant Util.Locales.Locale := Context.Get_Locale;
App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application;
Bundle : ASF.Locales.Bundle;
begin
if Pos > 0 then
App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1),
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last),
Message_Id (Pos + 1 .. Message_Id'Last));
else
App.Load_Bundle (Name => "messages",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
return Bundle.Get (Message_Id, Message_Id);
end if;
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E));
return Message_Id;
end Get_Message;
-- ------------------------------
-- Build a localized message.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) return Message is
Msg : constant String := Get_Message (Context, Message_Id);
Result : Message;
begin
Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg);
Result.Kind := Severity;
return Result;
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with one argument.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) return Message is
Args : ASF.Utils.Object_Array (1 .. 1);
begin
Args (1) := Util.Beans.Objects.To_Object (Param1);
return Get_Message (Context, Message_Id, Args, Severity);
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with two argument.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Param2 : in String;
Severity : in Messages.Severity := ERROR) return Message is
Args : ASF.Utils.Object_Array (1 .. 2);
begin
Args (1) := Util.Beans.Objects.To_Object (Param1);
Args (2) := Util.Beans.Objects.To_Object (Param2);
return Get_Message (Context, Message_Id, Args, Severity);
end Get_Message;
-- ------------------------------
-- Build a localized message and format the message with some arguments.
-- ------------------------------
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Args : in ASF.Utils.Object_Array;
Severity : in Messages.Severity := ERROR) return Message is
Msg : constant String := Get_Message (Context, Message_Id);
Result : Message;
begin
Result.Kind := Severity;
ASF.Utils.Formats.Format (Msg, Args, Result.Summary);
return Result;
end Get_Message;
-- ------------------------------
-- Add a localized global message in the faces context.
-- ------------------------------
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) is
Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity);
begin
Context.Add_Message (Client_Id => "", Message => Msg);
end Add_Message;
-- ------------------------------
-- Add a localized global message in the faces context.
-- ------------------------------
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) is
Msg : constant Message := Get_Message (Context, Message_Id, Severity);
begin
Context.Add_Message (Client_Id => "", Message => Msg);
end Add_Message;
-- ------------------------------
-- Add a localized global message in the current faces context.
-- ------------------------------
procedure Add_Message (Message_Id : in String;
Severity : in Messages.Severity := ERROR) is
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
Add_Message (Context.all, Message_Id, Severity);
end Add_Message;
end ASF.Applications.Messages.Factory;
|
Use the context locale to localize the message
|
Use the context locale to localize the message
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
83739777c2ea2135b6ea6810f5e4a9c8a11123e2
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "03";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "10";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
Bump to version 1.10 (enhancement is worth a release)
|
Bump to version 1.10 (enhancement is worth a release)
The repository rebuild time improvement is a high-visibility request
so it's worth a new release by itself.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
462bab510c8dbf17215a0b047217c132f383d93d
|
src/sys/os-windows/util-processes-os.ads
|
src/sys/os-windows/util-processes-os.ads
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 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.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
type Wchar_Ptr is access all Interfaces.C.wchar_array;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
In_File : Wchar_Ptr := null;
Out_File : Wchar_Ptr := null;
Err_File : Wchar_Ptr := null;
Dir : Wchar_Ptr := null;
To_Close : File_Type_Array_Access;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 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.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
subtype Wchar_Ptr is Util.Systems.Os.Wchar_Ptr;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
In_File : Wchar_Ptr := null;
Out_File : Wchar_Ptr := null;
Err_File : Wchar_Ptr := null;
Dir : Wchar_Ptr := null;
To_Close : File_Type_Array_Access;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
Use Wchar_Ptr definition from Util.Systems.Os package
|
Use Wchar_Ptr definition from Util.Systems.Os package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0368cb6033b1c29046be3167860c50f1ea9751c0
|
ARM/STM32/drivers/uart_stm32f4/stm32-usarts.ads
|
ARM/STM32/drivers/uart_stm32f4/stm32-usarts.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_usart.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of USARTS HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- USART from ST Microelectronics.
-- Note that there are board implementation assumptions represented by the
-- private function APB_Clock.
pragma Restrictions (No_Elaboration_Code);
with System;
with HAL.UART; use HAL.UART;
private with STM32_SVD.USART;
package STM32.USARTs is
type Internal_USART is limited private;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with private;
procedure Enable (This : in out USART) with
Post => Enabled (This),
Inline;
procedure Disable (This : in out USART) with
Post => not Enabled (This),
Inline;
function Enabled (This : USART) return Boolean with Inline;
procedure Receive (This : USART; Data : out UInt9) with Inline;
-- reads Device.DR into Data
function Current_Input (This : USART) return UInt9 with Inline;
-- returns Device.DR
procedure Transmit (This : in out USART; Data : UInt9) with Inline;
function Tx_Ready (This : USART) return Boolean with Inline;
function Rx_Ready (This : USART) return Boolean with Inline;
type Stop_Bits is (Stopbits_1, Stopbits_2) with Size => 2;
for Stop_Bits use (Stopbits_1 => 0, Stopbits_2 => 2#10#);
procedure Set_Stop_Bits (This : in out USART; To : Stop_Bits);
type Word_Lengths is (Word_Length_8, Word_Length_9);
procedure Set_Word_Length (This : in out USART; To : Word_Lengths);
type Parities is (No_Parity, Even_Parity, Odd_Parity);
procedure Set_Parity (This : in out USART; To : Parities);
subtype Baud_Rates is Word;
procedure Set_Baud_Rate (This : in out USART; To : Baud_Rates);
type Oversampling_Modes is (Oversampling_By_8, Oversampling_By_16);
-- oversampling by 16 is the default
procedure Set_Oversampling_Mode
(This : in out USART;
To : Oversampling_Modes);
type UART_Modes is (Rx_Mode, Tx_Mode, Tx_Rx_Mode);
procedure Set_Mode (This : in out USART; To : UART_Modes);
type Flow_Control is
(No_Flow_Control,
RTS_Flow_Control,
CTS_Flow_Control,
RTS_CTS_Flow_Control);
procedure Set_Flow_Control (This : in out USART; To : Flow_Control);
type USART_Interrupt is
(Parity_Error,
Transmit_Data_Register_Empty,
Transmission_Complete,
Received_Data_Not_Empty,
Idle_Line_Detection,
Line_Break_Detection,
Clear_To_Send,
Error);
procedure Enable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => Interrupt_Enabled (This, Source),
Inline;
procedure Disable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => not Interrupt_Enabled (This, Source),
Inline;
function Interrupt_Enabled
(This : USART;
Source : USART_Interrupt)
return Boolean
with Inline;
type USART_Status_Flag is
(Parity_Error_Indicated,
Framing_Error_Indicated,
USART_Noise_Error_Indicated,
Overrun_Error_Indicated,
Idle_Line_Detection_Indicated,
Read_Data_Register_Not_Empty,
Transmission_Complete_Indicated,
Transmit_Data_Register_Empty,
Line_Break_Detection_Indicated,
Clear_To_Send_Indicated);
function Status (This : USART; Flag : USART_Status_Flag) return Boolean
with Inline;
procedure Clear_Status (This : in out USART; Flag : USART_Status_Flag)
with Inline;
procedure Enable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This);
procedure Disable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => not DMA_Transmit_Requests_Enabled (This);
function DMA_Transmit_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Enable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This);
procedure Disable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => not DMA_Receive_Requests_Enabled (This);
function DMA_Receive_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Pause_DMA_Transmission (This : in out USART)
renames Disable_DMA_Transmit_Requests;
procedure Resume_DMA_Transmission (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This) and
Enabled (This);
procedure Pause_DMA_Reception (This : in out USART)
renames Disable_DMA_Receive_Requests;
procedure Resume_DMA_Reception (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This) and
Enabled (This);
function Data_Register_Address (This : USART) return System.Address with
Inline;
-- Returns the address of the USART Data Register. This is exported
-- STRICTLY for the sake of clients driving a USART via DMA. All other
-- clients of this package should use the procedural interfaces Transmit
-- and Receive instead of directly accessing the Data Register!
-- Seriously, don't use this function otherwise.
-----------------------------
-- HAL.UART implementation --
-----------------------------
overriding
function Data_Size (This : USART) return HAL.UART.UART_Data_Size;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
private
function APB_Clock (This : USART) return Word with Inline;
-- Returns either APB1 or APB2 clock rate, in Hertz, depending on the
-- USART. For the sake of not making this package board-specific, we assume
-- that we are given a valid USART object at a valid address, AND that the
-- USART devices really are configured such that only 1 and 6 are on APB2.
-- Therefore, if a board has additional USARTs beyond USART6, eg USART8 on
-- the F429I Discovery board, they better conform to that assumption.
-- See Note # 2 in each of Tables 139-141 of the RM on pages 970 - 972.
type Internal_USART is new STM32_SVD.USART.USART2_Peripheral;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with null record;
end STM32.USARTs;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_usart.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of USARTS HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- USART from ST Microelectronics.
-- Note that there are board implementation assumptions represented by the
-- private function APB_Clock.
with System;
with HAL.UART; use HAL.UART;
private with STM32_SVD.USART;
package STM32.USARTs is
type Internal_USART is limited private;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with private;
procedure Enable (This : in out USART) with
Post => Enabled (This),
Inline;
procedure Disable (This : in out USART) with
Post => not Enabled (This),
Inline;
function Enabled (This : USART) return Boolean with Inline;
procedure Receive (This : USART; Data : out UInt9) with Inline;
-- reads Device.DR into Data
function Current_Input (This : USART) return UInt9 with Inline;
-- returns Device.DR
procedure Transmit (This : in out USART; Data : UInt9) with Inline;
function Tx_Ready (This : USART) return Boolean with Inline;
function Rx_Ready (This : USART) return Boolean with Inline;
type Stop_Bits is (Stopbits_1, Stopbits_2) with Size => 2;
for Stop_Bits use (Stopbits_1 => 0, Stopbits_2 => 2#10#);
procedure Set_Stop_Bits (This : in out USART; To : Stop_Bits);
type Word_Lengths is (Word_Length_8, Word_Length_9);
procedure Set_Word_Length (This : in out USART; To : Word_Lengths);
type Parities is (No_Parity, Even_Parity, Odd_Parity);
procedure Set_Parity (This : in out USART; To : Parities);
subtype Baud_Rates is Word;
procedure Set_Baud_Rate (This : in out USART; To : Baud_Rates);
type Oversampling_Modes is (Oversampling_By_8, Oversampling_By_16);
-- oversampling by 16 is the default
procedure Set_Oversampling_Mode
(This : in out USART;
To : Oversampling_Modes);
type UART_Modes is (Rx_Mode, Tx_Mode, Tx_Rx_Mode);
procedure Set_Mode (This : in out USART; To : UART_Modes);
type Flow_Control is
(No_Flow_Control,
RTS_Flow_Control,
CTS_Flow_Control,
RTS_CTS_Flow_Control);
procedure Set_Flow_Control (This : in out USART; To : Flow_Control);
type USART_Interrupt is
(Parity_Error,
Transmit_Data_Register_Empty,
Transmission_Complete,
Received_Data_Not_Empty,
Idle_Line_Detection,
Line_Break_Detection,
Clear_To_Send,
Error);
procedure Enable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => Interrupt_Enabled (This, Source),
Inline;
procedure Disable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => not Interrupt_Enabled (This, Source),
Inline;
function Interrupt_Enabled
(This : USART;
Source : USART_Interrupt)
return Boolean
with Inline;
type USART_Status_Flag is
(Parity_Error_Indicated,
Framing_Error_Indicated,
USART_Noise_Error_Indicated,
Overrun_Error_Indicated,
Idle_Line_Detection_Indicated,
Read_Data_Register_Not_Empty,
Transmission_Complete_Indicated,
Transmit_Data_Register_Empty,
Line_Break_Detection_Indicated,
Clear_To_Send_Indicated);
function Status (This : USART; Flag : USART_Status_Flag) return Boolean
with Inline;
procedure Clear_Status (This : in out USART; Flag : USART_Status_Flag)
with Inline;
procedure Enable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This);
procedure Disable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => not DMA_Transmit_Requests_Enabled (This);
function DMA_Transmit_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Enable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This);
procedure Disable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => not DMA_Receive_Requests_Enabled (This);
function DMA_Receive_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Pause_DMA_Transmission (This : in out USART)
renames Disable_DMA_Transmit_Requests;
procedure Resume_DMA_Transmission (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This) and
Enabled (This);
procedure Pause_DMA_Reception (This : in out USART)
renames Disable_DMA_Receive_Requests;
procedure Resume_DMA_Reception (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This) and
Enabled (This);
function Data_Register_Address (This : USART) return System.Address with
Inline;
-- Returns the address of the USART Data Register. This is exported
-- STRICTLY for the sake of clients driving a USART via DMA. All other
-- clients of this package should use the procedural interfaces Transmit
-- and Receive instead of directly accessing the Data Register!
-- Seriously, don't use this function otherwise.
-----------------------------
-- HAL.UART implementation --
-----------------------------
overriding
function Data_Size (This : USART) return HAL.UART.UART_Data_Size;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
private
function APB_Clock (This : USART) return Word with Inline;
-- Returns either APB1 or APB2 clock rate, in Hertz, depending on the
-- USART. For the sake of not making this package board-specific, we assume
-- that we are given a valid USART object at a valid address, AND that the
-- USART devices really are configured such that only 1 and 6 are on APB2.
-- Therefore, if a board has additional USARTs beyond USART6, eg USART8 on
-- the F429I Discovery board, they better conform to that assumption.
-- See Note # 2 in each of Tables 139-141 of the RM on pages 970 - 972.
type Internal_USART is new STM32_SVD.USART.USART2_Peripheral;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with null record;
end STM32.USARTs;
|
remove No_Elaboration_Code restriction
|
STM32.USART: remove No_Elaboration_Code restriction
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
|
b74739573fd74f3234a571a100f28bf9fa0779c8
|
orka/src/orka/implementation/orka-rendering-programs-modules.adb
|
orka/src/orka/implementation/orka-rendering-programs-modules.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with GL.Debug;
with Orka.Strings;
with Orka.Terminals;
package body Orka.Rendering.Programs.Modules is
use GL.Debug;
package Messages is new GL.Debug.Messages (Third_Party, Other);
function Trim_Image (Value : Integer) return String is
(Orka.Strings.Trim (Integer'Image (Value)));
package L1 renames Ada.Characters.Latin_1;
use Orka.Strings;
procedure Log_Error_With_Source (Text, Info_Log, Message : String) is
package SF renames Ada.Strings.Fixed;
Extra_Rows : constant := 1;
Line_Number_Padding : constant := 2;
Separator : constant String := " | ";
use SF;
use all type Orka.Terminals.Color;
use all type Orka.Terminals.Style;
begin
declare
Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3);
Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2);
Message_Kind_Color : constant Orka.Terminals.Color :=
(if +Message_Parts (1) = "error" then
Red
elsif +Message_Parts (1) = "warning" then
Yellow
elsif +Message_Parts (1) = "note" then
Cyan
else
Default);
Message_Kind : constant String :=
Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color);
Message_Value : constant String :=
Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold);
-------------------------------------------------------------------------
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Error_Row : constant Positive :=
Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1));
First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows);
Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows);
Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding;
begin
Messages.Log (High, Message);
for Row_Index in First_Row .. Last_Row loop
declare
Row_Image : constant String :=
SF.Tail (Trim (Row_Index'Image), Line_Digits);
Row_Image_Colorized : constant String :=
Orka.Terminals.Colorize (Row_Image, Attribute => Dark);
Line_Image : constant String := +Lines (Row_Index);
First_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward);
Last_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward);
Error_Indicator : constant String :=
Orka.Terminals.Colorize
(Natural'Max (0, First_Index_Line - 1) * " " &
(Last_Index_Line - First_Index_Line + 1) * "^",
Foreground => Green,
Attribute => Bold);
Prefix_Image : constant String :=
(Row_Image'Length + Separator'Length) * " ";
begin
Messages.Log (High, Row_Image_Colorized & Separator & Line_Image);
if Row_Index = Error_Row then
Messages.Log (High, Prefix_Image & Error_Indicator);
Messages.Log (High, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value);
end if;
end;
end loop;
end;
exception
when others =>
-- Continue if parsing Info_Log fails
null;
end Log_Error_With_Source;
procedure Load_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Location : Resources.Locations.Location_Ptr;
Path : String) is
begin
if Path /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
Source : constant Resources.Byte_Array_Pointers.Pointer
:= Location.Read_Data (Path);
Text : String renames Resources.Convert (Source.Get);
begin
Shader.Set_Source (Text);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Text, +Part, "Compiling shader " & Path & " failed:");
end loop;
raise Shader_Compile_Error with Path & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled shader " & Path);
Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Text)) &
" lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Load_And_Compile;
procedure Set_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Source : String) is
begin
if Source /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
begin
Shader.Set_Source (Source);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Source, +Part,
"Compiling " & Shader_Kind'Image & " shader failed:");
end loop;
raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled string with " &
Trim_Image (Source'Length) & " characters");
Messages.Log (Notification, " size: " &
Trim_Image (Orka.Strings.Lines (Source)) & " lines");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Set_And_Compile;
function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "")
return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Set_And_Compile (Result, Vertex_Shader, VS);
Set_And_Compile (Result, Tess_Control_Shader, TCS);
Set_And_Compile (Result, Tess_Evaluation_Shader, TES);
Set_And_Compile (Result, Geometry_Shader, GS);
Set_And_Compile (Result, Fragment_Shader, FS);
Set_And_Compile (Result, Compute_Shader, CS);
end return;
end Create_Module_From_Sources;
function Create_Module
(Location : Resources.Locations.Location_Ptr;
VS, TCS, TES, GS, FS, CS : String := "") return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Load_And_Compile (Result, Vertex_Shader, Location, VS);
Load_And_Compile (Result, Tess_Control_Shader, Location, TCS);
Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES);
Load_And_Compile (Result, Geometry_Shader, Location, GS);
Load_And_Compile (Result, Fragment_Shader, Location, FS);
Load_And_Compile (Result, Compute_Shader, Location, CS);
end return;
end Create_Module;
procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is
use GL.Objects.Shaders;
procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is
Holder : Shader_Holder.Holder renames Subject.Shaders (Stage);
begin
if not Holder.Is_Empty then
Program.GL_Program.Attach (Holder.Element);
end if;
end Attach;
begin
for Module of Modules loop
Attach (Module, Vertex_Shader);
Attach (Module, Tess_Control_Shader);
Attach (Module, Tess_Evaluation_Shader);
Attach (Module, Geometry_Shader);
Attach (Module, Fragment_Shader);
Attach (Module, Compute_Shader);
end loop;
end Attach_Shaders;
procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is
use GL.Objects.Shaders;
procedure Detach (Holder : Shader_Holder.Holder) is
begin
if not Holder.Is_Empty then
Program.GL_Program.Detach (Holder.Element);
end if;
end Detach;
begin
for Module of Modules loop
Detach (Module.Shaders (Vertex_Shader));
Detach (Module.Shaders (Tess_Control_Shader));
Detach (Module.Shaders (Tess_Evaluation_Shader));
Detach (Module.Shaders (Geometry_Shader));
Detach (Module.Shaders (Fragment_Shader));
Detach (Module.Shaders (Compute_Shader));
end loop;
end Detach_Shaders;
end Orka.Rendering.Programs.Modules;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Orka.Logging;
with Orka.Strings;
with Orka.Terminals;
package body Orka.Rendering.Programs.Modules is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
package Messages is new Orka.Logging.Messages (Shader_Compiler);
function Trim_Image (Value : Integer) return String is
(Orka.Strings.Trim (Integer'Image (Value)));
package L1 renames Ada.Characters.Latin_1;
use Orka.Strings;
procedure Log_Error_With_Source (Text, Info_Log, Message : String) is
package SF renames Ada.Strings.Fixed;
Extra_Rows : constant := 1;
Line_Number_Padding : constant := 2;
Separator : constant String := " | ";
use SF;
use all type Orka.Terminals.Color;
use all type Orka.Terminals.Style;
begin
declare
Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3);
Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2);
Message_Kind_Color : constant Orka.Terminals.Color :=
(if +Message_Parts (1) = "error" then
Red
elsif +Message_Parts (1) = "warning" then
Yellow
elsif +Message_Parts (1) = "note" then
Cyan
else
Default);
Message_Kind : constant String :=
Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color);
Message_Value : constant String :=
Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold);
-------------------------------------------------------------------------
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Error_Row : constant Positive :=
Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1));
First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows);
Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows);
Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding;
begin
Messages.Log (Error, Message);
for Row_Index in First_Row .. Last_Row loop
declare
Row_Image : constant String :=
SF.Tail (Trim (Row_Index'Image), Line_Digits);
Row_Image_Colorized : constant String :=
Orka.Terminals.Colorize (Row_Image, Attribute => Dark);
Line_Image : constant String := +Lines (Row_Index);
First_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward);
Last_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward);
Error_Indicator : constant String :=
Orka.Terminals.Colorize
(Natural'Max (0, First_Index_Line - 1) * " " &
(Last_Index_Line - First_Index_Line + 1) * "^",
Foreground => Green,
Attribute => Bold);
Prefix_Image : constant String :=
(Row_Image'Length + Separator'Length) * " ";
begin
Messages.Log (Error, Row_Image_Colorized & Separator & Line_Image);
if Row_Index = Error_Row then
Messages.Log (Error, Prefix_Image & Error_Indicator);
Messages.Log (Error, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value);
end if;
end;
end loop;
end;
exception
when others =>
-- Continue if parsing Info_Log fails
null;
end Log_Error_With_Source;
procedure Load_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Location : Resources.Locations.Location_Ptr;
Path : String) is
begin
if Path /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
Source : constant Resources.Byte_Array_Pointers.Pointer
:= Location.Read_Data (Path);
Text : String renames Resources.Convert (Source.Get);
begin
Shader.Set_Source (Text);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Text, +Part, "Compiling shader " & Path & " failed:");
end loop;
raise Shader_Compile_Error with Path & ":" & Log;
end;
end if;
Messages.Log (Debug, "Compiled shader " & Path);
Messages.Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Text)) &
" lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)");
Messages.Log (Debug, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Load_And_Compile;
procedure Set_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Source : String) is
begin
if Source /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
begin
Shader.Set_Source (Source);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Source, +Part,
"Compiling " & Shader_Kind'Image & " shader failed:");
end loop;
raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log;
end;
end if;
Messages.Log (Debug, "Compiled string with " &
Trim_Image (Source'Length) & " characters");
Messages.Log (Debug, " size: " &
Trim_Image (Orka.Strings.Lines (Source)) & " lines");
Messages.Log (Debug, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Set_And_Compile;
function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "")
return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Set_And_Compile (Result, Vertex_Shader, VS);
Set_And_Compile (Result, Tess_Control_Shader, TCS);
Set_And_Compile (Result, Tess_Evaluation_Shader, TES);
Set_And_Compile (Result, Geometry_Shader, GS);
Set_And_Compile (Result, Fragment_Shader, FS);
Set_And_Compile (Result, Compute_Shader, CS);
end return;
end Create_Module_From_Sources;
function Create_Module
(Location : Resources.Locations.Location_Ptr;
VS, TCS, TES, GS, FS, CS : String := "") return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Load_And_Compile (Result, Vertex_Shader, Location, VS);
Load_And_Compile (Result, Tess_Control_Shader, Location, TCS);
Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES);
Load_And_Compile (Result, Geometry_Shader, Location, GS);
Load_And_Compile (Result, Fragment_Shader, Location, FS);
Load_And_Compile (Result, Compute_Shader, Location, CS);
end return;
end Create_Module;
procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is
use GL.Objects.Shaders;
procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is
Holder : Shader_Holder.Holder renames Subject.Shaders (Stage);
begin
if not Holder.Is_Empty then
Program.GL_Program.Attach (Holder.Element);
end if;
end Attach;
begin
for Module of Modules loop
Attach (Module, Vertex_Shader);
Attach (Module, Tess_Control_Shader);
Attach (Module, Tess_Evaluation_Shader);
Attach (Module, Geometry_Shader);
Attach (Module, Fragment_Shader);
Attach (Module, Compute_Shader);
end loop;
end Attach_Shaders;
procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is
use GL.Objects.Shaders;
procedure Detach (Holder : Shader_Holder.Holder) is
begin
if not Holder.Is_Empty then
Program.GL_Program.Detach (Holder.Element);
end if;
end Detach;
begin
for Module of Modules loop
Detach (Module.Shaders (Vertex_Shader));
Detach (Module.Shaders (Tess_Control_Shader));
Detach (Module.Shaders (Tess_Evaluation_Shader));
Detach (Module.Shaders (Geometry_Shader));
Detach (Module.Shaders (Fragment_Shader));
Detach (Module.Shaders (Compute_Shader));
end loop;
end Detach_Shaders;
end Orka.Rendering.Programs.Modules;
|
Use Orka.Logging instead of GL.Debug to log errors in shaders
|
orka: Use Orka.Logging instead of GL.Debug to log errors in shaders
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
90c6339ec798dbe42343d82df10bd2a909c06f65
|
regtests/security-oauth-servers-tests.adb
|
regtests/security-oauth-servers-tests.adb
|
-----------------------------------------------------------------------
-- Security-oauth-servers-tests - Unit tests for server side OAuth
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate",
Test_Bad_Token'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Test_Token_Password (T : in out Test) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20,
"Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null,
"Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name,
"Invalid user name in the principal");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
end loop;
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant,
"Expecting Revoked_Grant for the authenticate");
end loop;
-- Change application token expiration time to 1 second.
App.Expire_Timeout := 1.0;
Apps.Add_Application (App);
-- Make the access token.
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null,
"Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth,
"Expecting valid auth principal");
end loop;
-- Wait for the token to expire.
delay 2.0;
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Expired_Grant,
"Expecting Expired when the access token is checked");
end loop;
end Test_Token_Password;
-- ------------------------------
-- Test the access token validation with invalid tokens (bad formed).
-- ------------------------------
procedure Test_Bad_Token (T : in out Test) is
Manager : Auth_Manager;
Auth_Grant : Grant_Type;
begin
Manager.Authenticate ("x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate (".", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
end Test_Bad_Token;
end Security.OAuth.Servers.Tests;
|
-----------------------------------------------------------------------
-- Security-oauth-servers-tests - Unit tests for server side OAuth
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate",
Test_Bad_Token'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load",
Test_Load_Registry'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Test_Token_Password (T : in out Test) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20,
"Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null,
"Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name,
"Invalid user name in the principal");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
end loop;
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant,
"Expecting Revoked_Grant for the authenticate");
end loop;
-- Change application token expiration time to 1 second.
App.Expire_Timeout := 1.0;
Apps.Add_Application (App);
-- Make the access token.
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null,
"Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth,
"Expecting valid auth principal");
end loop;
-- Wait for the token to expire.
delay 2.0;
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Expired_Grant,
"Expecting Expired when the access token is checked");
end loop;
end Test_Token_Password;
-- ------------------------------
-- Test the access token validation with invalid tokens (bad formed).
-- ------------------------------
procedure Test_Bad_Token (T : in out Test) is
Manager : Auth_Manager;
Auth_Grant : Grant_Type;
begin
Manager.Authenticate ("x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate (".", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
end Test_Bad_Token;
-- ------------------------------
-- Test the loading configuration files for the File_Registry.
-- ------------------------------
procedure Test_Load_Registry (T : in out Test) is
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps");
Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1");
Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Params.Set_Parameter (Security.OAuth.USERNAME, "joe");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
end Test_Load_Registry;
end Security.OAuth.Servers.Tests;
|
Implement the Test_Load_Registry procedure to check the loading of applications and users in the File_Registry and verify they are recognized upon OAuth password access
|
Implement the Test_Load_Registry procedure to check the loading of applications and
users in the File_Registry and verify they are recognized upon OAuth password access
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ef7533bf9eb20104acff7fe240699f9955210e1d
|
src/wiki-render.ads
|
src/wiki-render.ads
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer;
Doc : in Wiki.Documents.Document) is null;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
--
-- @include wiki-render-html.ads
-- @include wiki-render-text.ads
-- @include wiki-render-wiki.ads
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer;
Doc : in Wiki.Documents.Document) is null;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
Declare the To_Char function
|
Declare the To_Char function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a2bd0ee2b35582fd3a17e8cc40be77ffe0843289
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- 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.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Remove_Tag;
end AWA.Tags.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- 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.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Remove_Tag;
end AWA.Tags.Modules.Tests;
|
Fix the tags unit test
|
Fix the tags unit test
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
ed43b73a701a6d42cfe8338ec3eae798ab993475
|
regtests/ado-testsuite.adb
|
regtests/ado-testsuite.adb
|
-----------------------------------------------------------------------
-- ado-testsuite -- Testsuite for ADO
-- 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.Tests;
with ADO.Schemas.Tests;
with ADO.Objects.Tests;
with ADO.Queries.Tests;
package body ADO.Testsuite is
use ADO.Tests;
Tests : aliased AUnit.Test_Suites.Test_Suite;
function Suite return AUnit.Test_Suites.Access_Test_Suite is
Ret : constant AUnit.Test_Suites.Access_Test_Suite := Tests'Access;
begin
-- ADO.Objects.Tests.Add_Tests (Ret);
-- ADO.Tests.Add_Tests (Ret);
-- ADO.Schemas.Tests.Add_Tests (Ret);
ADO.Queries.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ADO.Testsuite;
|
-----------------------------------------------------------------------
-- ado-testsuite -- Testsuite for ADO
-- 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 ADO.Tests;
with ADO.Schemas.Tests;
with ADO.Objects.Tests;
with ADO.Queries.Tests;
package body ADO.Testsuite is
use ADO.Tests;
Tests : aliased AUnit.Test_Suites.Test_Suite;
function Suite return AUnit.Test_Suites.Access_Test_Suite is
Ret : constant AUnit.Test_Suites.Access_Test_Suite := Tests'Access;
begin
ADO.Objects.Tests.Add_Tests (Ret);
ADO.Tests.Add_Tests (Ret);
ADO.Schemas.Tests.Add_Tests (Ret);
ADO.Queries.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ADO.Testsuite;
|
Add the new unit tests
|
Add the new unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
7334c107a44e6bd829f8eab3ed718a7170d007fc
|
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;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- 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;
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;
|
Define the Setup procedure
|
Define the Setup procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1f40ee7362a6a54a4b02331d6978864a0d932155
|
src/babel-stores-local.adb
|
src/babel-stores-local.adb
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Interfaces;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Ada.Directories.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Size;
exception
when Constraint_Error =>
return Ada.Directories.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.Directory_Vector_Access;
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
New_File : Babel.Files.File;
Child : Babel.Files.Directory;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
begin
if Kind = Ordinary_File then
if Filter.Is_Accepted (Kind, Path, Name) then
New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
New_File.Path := Ada.Strings.Unbounded.To_Unbounded_String (Path);
New_File.Size := Get_File_Size (Ent);
Into.Add_File (Path, New_File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
-- if Into.Children = null then
-- Into.Children := new Babel.Files.Directory_Vector;
-- end if;
-- Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
-- Into.Children.Append (Child);
-- Into.Tot_Dirs := Into.Tot_Dirs + 1;
Into.Add_Directory (Path, Name);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
end Babel.Stores.Local;
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Interfaces;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Ada.Directories.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Size;
exception
when Constraint_Error =>
return Ada.Directories.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
begin
if Kind = Ordinary_File then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = null then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (Get_File_Size (Ent));
Into.Add_File (Path, New_File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Child := Info.Find (Name);
if Child = null then
Child := Into.Create (Name);
end if;
Into.Add_Directory (Child);
-- if Into.Children = null then
-- Into.Children := new Babel.Files.Directory_Vector;
-- end if;
-- Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
-- Into.Children.Append (Child);
-- Into.Tot_Dirs := Into.Tot_Dirs + 1;
Into.Add_Directory (Path, Name);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
end Babel.Stores.Local;
|
Use the File_Container interface to create and populate the container instance when we scan a directory
|
Use the File_Container interface to create and populate the container
instance when we scan a directory
|
Ada
|
apache-2.0
|
stcarrez/babel
|
c2c56067ab14c270075d990f6668fa15a4ec3417
|
src/security-openid.ads
|
src/security-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Util.Http;
with Security.Permissions;
-- 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
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The process is the following:
--
-- o <b>Initialize</b> is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- o <b>Discover</b> is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- o <b>Associate</b> is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- o <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- o The user should be redirected to the authentication URL.
-- o The OpenID provider authenticate the user and redirects the user to the callback CB.
-- o The association is decoded from the callback parameter.
-- o <b>Verify</b> is called with the association to check the result and
-- obtain the authentication results.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Security.Permissions;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The process is the following:
--
-- o <b>Initialize</b> is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- o <b>Discover</b> is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- o <b>Associate</b> is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- o <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- o The user should be redirected to the authentication URL.
-- o The OpenID provider authenticate the user and redirects the user to the callback CB.
-- o The association is decoded from the callback parameter.
-- o <b>Verify</b> is called with the association to check the result and
-- obtain the authentication results.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Include in generated dynamo documentation
|
Include in generated dynamo documentation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
425d580258908501f8b3a29c617fd9307c0a2cf9
|
src/ado-sequences-hilo.adb
|
src/ado-sequences-hilo.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
with ADO.SQL;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use Sequence_Maps;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : in Session_Factory_Access)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : in out Objects.Object_Record'Class) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id.Set_Key_Value (Gen.Next_Id);
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
for Retry in 1 .. 10 loop
-- Allocate a new sequence within a transaction.
declare
Query : ADO.SQL.Query;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Query.Set_Filter ("name = ?");
Query.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Session => DB, Query => Query, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Create (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying {0}/100",
Util.Strings.Image (Retry));
DB.Rollback;
delay 0.01 * Retry;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
Log.Error ("Cannot allocate sequence range");
raise ADO.Objects.ALLOCATE_ID_ERROR with "Cannot allocate unique identifier";
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
with ADO.SQL;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : in Session_Factory_Access)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : in out Objects.Object_Record'Class) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id.Set_Key_Value (Gen.Next_Id);
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
for Retry in 1 .. 10 loop
-- Allocate a new sequence within a transaction.
declare
Query : ADO.SQL.Query;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Query.Set_Filter ("name = ?");
Query.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Session => DB, Query => Query, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Create (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying {0}/100",
Util.Strings.Image (Retry));
DB.Rollback;
delay 0.01 * Retry;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
Log.Error ("Cannot allocate sequence range");
raise ADO.Objects.ALLOCATE_ID_ERROR with "Cannot allocate unique identifier";
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
Remove unecessary use clause
|
Remove unecessary use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
32c8cbe6caa6ed3bc1bb9a4d44c1be3ab84d52b1
|
src/asf-lifecycles.adb
|
src/asf-lifecycles.adb
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
declare
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
Event : ASF.Events.Phases.Phase_Event (Phase);
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end Before_Phase;
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end After_Phase;
begin
Context.Set_Current_Phase (Phase);
-- Call the before phase listeners if there are some.
if not Listeners.Is_Empty then
Listeners.Iterate (Before_Phase'Access);
end if;
begin
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
if not Listeners.Is_Empty then
Listeners.Iterate (After_Phase'Access);
end if;
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE);
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
-- ------------------------------
-- Add a phase listener in the lifecycle controller.
-- ------------------------------
procedure Add_Phase_Listener (Controller : in out Lifecycle;
Listener : in ASF.Events.Phases.Phase_Listener_Access) is
begin
Controller.Listeners.Append (Listener);
end Add_Phase_Listener;
end ASF.Lifecycles;
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
declare
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
Event : ASF.Events.Phases.Phase_Event (Phase);
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end Before_Phase;
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.After_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end After_Phase;
begin
Context.Set_Current_Phase (Phase);
-- Call the before phase listeners if there are some.
Listeners.Iterate (Before_Phase'Access);
begin
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
Listeners.Iterate (After_Phase'Access);
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE);
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
-- ------------------------------
-- Add a phase listener in the lifecycle controller.
-- ------------------------------
procedure Add_Phase_Listener (Controller : in out Lifecycle;
Listener : in ASF.Events.Phases.Phase_Listener_Access) is
begin
Controller.Listeners.Append (Listener);
end Add_Phase_Listener;
end ASF.Lifecycles;
|
Fix call to After_Phase listener
|
Fix call to After_Phase listener
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
d97c714991ea27544fc578420f1a1dba31e8b146
|
src/asf-contexts-flash.adb
|
src/asf-contexts-flash.adb
|
-----------------------------------------------------------------------
-- contexts-facelets-flash -- Flash context
-- 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.Sessions;
with ASF.Applications.Messages.Utils;
package body ASF.Contexts.Flash is
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Instance : Flash_Bean_Access;
begin
Flash.Get_Execute_Flash (Instance);
if Util.Beans.Objects.Is_Null (Value) then
Instance.Attributes.Delete (Name);
else
Instance.Attributes.Include (Name, Value);
end if;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in Unbounded_String;
Value : in Util.Beans.Objects.Object) is
begin
Flash.Set_Attribute (To_String (Name), Value);
end Set_Attribute;
-- ------------------------------
-- Get the attribute with the given name from the 'previous' flash context.
-- ------------------------------
function Get_Attribute (Flash : in Flash_Context;
Name : in String) return Util.Beans.Objects.Object is
begin
if Flash.Previous = null then
return Util.Beans.Objects.Null_Object;
else
declare
Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end if;
end Get_Attribute;
-- Keep in the flash context the request attribute identified by the name <b>Name</b>.
procedure Keep (Flash : in out Flash_Context;
Name : in String) is
begin
null;
end Keep;
-- Returns True if the <b>Redirect</b> property was set on the previous flash instance.
function Is_Redirect (Flash : in Flash_Context) return Boolean is
begin
return False;
end Is_Redirect;
-- Set this property to True to indicate to the next request on this session will be
-- a redirect. After this call, the next request will return the <b>Redirect</b> value
-- when the <b>Is_Redirect</b> function will be called.
procedure Set_Redirect (Flash : in out Flash_Context;
Redirect : in Boolean) is
begin
null;
end Set_Redirect;
-- ------------------------------
-- Returns True if the faces messages that are queued in the faces context must be
-- preserved so they are accessible through the flash instance at the next request.
-- ------------------------------
function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is
begin
return Flash.Keep_Messages;
end Is_Keep_Messages;
-- ------------------------------
-- Set the keep messages property which controlls whether the faces messages
-- that are queued in the faces context must be preserved so they are accessible through
-- the flash instance at the next request.
-- ------------------------------
procedure Set_Keep_Messages (Flash : in out Flash_Context;
Value : in Boolean) is
begin
Flash.Keep_Messages := Value;
end Set_Keep_Messages;
-- ------------------------------
-- Perform any specific action before processing the phase referenced by <b>Phase</b>.
-- This operation is used to restore the flash context for a new request.
-- ------------------------------
procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
use type Util.Beans.Basic.Readonly_Bean_Access;
begin
-- Restore the flash bean instance from the session if there is one.
if Phase = ASF.Events.Phases.RESTORE_VIEW then
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
B : access Util.Beans.Basic.Readonly_Bean'Class;
begin
if S.Is_Valid then
Flash.Object := S.Get_Attribute ("asf.flash.bean");
B := Util.Beans.Objects.To_Bean (Flash.Object);
if B /= null and then B.all in Flash_Bean'Class then
Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access;
Context.Add_Messages ("", Flash.Previous.Messages);
end if;
end if;
end;
end if;
end Do_Pre_Phase_Actions;
-- ------------------------------
-- Perform any specific action after processing the phase referenced by <b>Phase</b>.
-- This operation is used to save the flash context
-- ------------------------------
procedure Do_Post_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
begin
if (Phase = ASF.Events.Phases.INVOKE_APPLICATION
or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then
Flash.Do_Last_Phase_Actions (Context);
end if;
end Do_Post_Phase_Actions;
-- ------------------------------
-- Perform the last actions that must be made to save the flash context in the session.
-- ------------------------------
procedure Do_Last_Phase_Actions (Flash : in out Flash_Context;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
S : ASF.Sessions.Session := Context.Get_Session;
begin
-- If we have to keep the messages, save them in the flash bean context if there are any.
if Flash.Keep_Messages then
declare
Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages ("");
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages);
end if;
end;
end if;
if S.Is_Valid then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object);
elsif Flash.Next /= null then
S := Context.Get_Session (Create => True);
end if;
if Flash.Next /= null then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access));
end if;
Flash.Last_Phase_Done := True;
end Do_Last_Phase_Actions;
procedure Get_Active_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Previous = null then
null;
end if;
Result := Flash.Previous;
end Get_Active_Flash;
procedure Get_Execute_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
Result := Flash.Next;
end Get_Execute_Flash;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Flash_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Contexts.Flash;
|
-----------------------------------------------------------------------
-- contexts-facelets-flash -- Flash context
-- 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.Sessions;
with ASF.Applications.Messages.Utils;
package body ASF.Contexts.Flash is
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Instance : Flash_Bean_Access;
begin
Flash.Get_Execute_Flash (Instance);
if Util.Beans.Objects.Is_Null (Value) then
Instance.Attributes.Delete (Name);
else
Instance.Attributes.Include (Name, Value);
end if;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in Unbounded_String;
Value : in Util.Beans.Objects.Object) is
begin
Flash.Set_Attribute (To_String (Name), Value);
end Set_Attribute;
-- ------------------------------
-- Get the attribute with the given name from the 'previous' flash context.
-- ------------------------------
function Get_Attribute (Flash : in Flash_Context;
Name : in String) return Util.Beans.Objects.Object is
begin
if Flash.Previous = null then
return Util.Beans.Objects.Null_Object;
else
declare
Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end if;
end Get_Attribute;
-- Keep in the flash context the request attribute identified by the name <b>Name</b>.
procedure Keep (Flash : in out Flash_Context;
Name : in String) is
begin
null;
end Keep;
-- ------------------------------
-- Returns True if the <b>Redirect</b> property was set on the previous flash instance.
-- ------------------------------
function Is_Redirect (Flash : in Flash_Context) return Boolean is
begin
return Flash.Previous /= null and then Flash.Previous.Redirect;
end Is_Redirect;
-- Set this property to True to indicate to the next request on this session will be
-- a redirect. After this call, the next request will return the <b>Redirect</b> value
-- when the <b>Is_Redirect</b> function will be called.
procedure Set_Redirect (Flash : in out Flash_Context;
Redirect : in Boolean) is
begin
null;
end Set_Redirect;
-- ------------------------------
-- Returns True if the faces messages that are queued in the faces context must be
-- preserved so they are accessible through the flash instance at the next request.
-- ------------------------------
function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is
begin
return Flash.Keep_Messages;
end Is_Keep_Messages;
-- ------------------------------
-- Set the keep messages property which controlls whether the faces messages
-- that are queued in the faces context must be preserved so they are accessible through
-- the flash instance at the next request.
-- ------------------------------
procedure Set_Keep_Messages (Flash : in out Flash_Context;
Value : in Boolean) is
begin
Flash.Keep_Messages := Value;
end Set_Keep_Messages;
-- ------------------------------
-- Perform any specific action before processing the phase referenced by <b>Phase</b>.
-- This operation is used to restore the flash context for a new request.
-- ------------------------------
procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
use type Util.Beans.Basic.Readonly_Bean_Access;
begin
-- Restore the flash bean instance from the session if there is one.
if Phase = ASF.Events.Phases.RESTORE_VIEW then
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
B : access Util.Beans.Basic.Readonly_Bean'Class;
begin
if S.Is_Valid then
Flash.Object := S.Get_Attribute ("asf.flash.bean");
B := Util.Beans.Objects.To_Bean (Flash.Object);
if B /= null and then B.all in Flash_Bean'Class then
Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access;
Context.Add_Messages ("", Flash.Previous.Messages);
end if;
end if;
end;
end if;
end Do_Pre_Phase_Actions;
-- ------------------------------
-- Perform any specific action after processing the phase referenced by <b>Phase</b>.
-- This operation is used to save the flash context
-- ------------------------------
procedure Do_Post_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
begin
if (Phase = ASF.Events.Phases.INVOKE_APPLICATION
or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then
Flash.Do_Last_Phase_Actions (Context);
end if;
end Do_Post_Phase_Actions;
-- ------------------------------
-- Perform the last actions that must be made to save the flash context in the session.
-- ------------------------------
procedure Do_Last_Phase_Actions (Flash : in out Flash_Context;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
S : ASF.Sessions.Session := Context.Get_Session;
begin
-- If we have to keep the messages, save them in the flash bean context if there are any.
if Flash.Keep_Messages then
declare
Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages ("");
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages);
end if;
end;
end if;
if S.Is_Valid then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object);
elsif Flash.Next /= null then
S := Context.Get_Session (Create => True);
end if;
if Flash.Next /= null then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access));
end if;
Flash.Last_Phase_Done := True;
end Do_Last_Phase_Actions;
procedure Get_Active_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Previous = null then
null;
end if;
Result := Flash.Previous;
end Get_Active_Flash;
procedure Get_Execute_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
Result := Flash.Next;
end Get_Execute_Flash;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Flash_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Contexts.Flash;
|
Implement the Is_Redirect function
|
Implement the Is_Redirect function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
fc78237ad82f08647910974519202878b99e4d44
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
type Block;
type Content_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Content_Access;
Last : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_Table : Boolean := False;
In_Html : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar;
Number : in Natural);
procedure Pop_List (P : in out Parser);
function Get_Current_Level (Parser : in Parser_Type) return Natural;
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_Table : Boolean := False;
In_Html : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar;
Number : in Natural);
procedure Pop_List (P : in out Parser);
function Get_Current_Level (Parser : in Parser_Type) return Natural;
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
Remove unused type Block
|
Remove unused type Block
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
30bf40c62ebdc3e7b0b723c6fa74748663d6020c
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management 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.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management 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.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- 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) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
Set the post publication date when the post is published for the first time
|
Set the post publication date when the post is published for the first time
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
48f539c3981529061e9005db4b122ac7a16c7d05
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Format_List_Bean",
Handler => AWA.Blogs.Beans.Create_Format_List_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref) is
Current_Entity : aliased AWA.Blogs.Models.Post_Ref := Post;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access
:= Current_Entity'Unchecked_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Event : AWA.Events.Module_Event;
begin
Event.Set_Event_Kind (Post_Publish_Event.Kind);
Event.Set_Parameter ("summary", Post.Get_Summary);
Event.Set_Parameter ("title", Post.Get_Title);
Event.Set_Parameter ("uri", Post.Get_Uri);
Event.Set_Parameter ("id", Bean);
Module.Send_Event (Event);
end Publish_Post;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Create_Date (Ada.Calendar.Clock);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
-- The post is published, post an event to trigger specific actions.
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Publish_Post (Model, Post);
end if;
end Create_Post;
-- ------------------------------
-- 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;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
Published : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
Published := Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null;
if Published then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
-- The post is published, post an event to trigger specific actions.
if Published then
Publish_Post (Model, Post);
end if;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Format_List_Bean",
Handler => AWA.Blogs.Beans.Create_Format_List_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref) is
Current_Entity : aliased AWA.Blogs.Models.Post_Ref := Post;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access
:= Current_Entity'Unchecked_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Event : AWA.Events.Module_Event;
begin
Event.Set_Event_Kind (Post_Publish_Event.Kind);
Event.Set_Parameter ("summary", Post.Get_Summary);
Event.Set_Parameter ("title", Post.Get_Title);
Event.Set_Parameter ("uri", Post.Get_Uri);
Event.Set_Parameter ("post", Bean);
Event.Set_Parameter ("author", Post.Get_Author.Get_Name);
Module.Send_Event (Event);
end Publish_Post;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- 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;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Create_Date (Ada.Calendar.Clock);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
-- The post is published, post an event to trigger specific actions.
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Publish_Post (Model, Post);
end if;
end Create_Post;
-- ------------------------------
-- 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;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
Published : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
Published := Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null;
if Published then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
-- The post is published, post an event to trigger specific actions.
if Published then
Publish_Post (Model, Post);
end if;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
Update the blog post publish event to add the author's name
|
Update the blog post publish event to add the author's name
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
eec526cf987427b4c53f0215ed8af180c6ffc5c2
|
src/asf-routes-servlets-rest.ads
|
src/asf-routes-servlets-rest.ads
|
-----------------------------------------------------------------------
-- asf-reoutes-servlets-rest -- Route for the REST 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.Rest;
package ASF.Routes.Servlets.Rest is
type Descriptor_Array is array (ASF.Rest.Method_Type) of ASF.Rest.Descriptor_Access;
-- The route has one descriptor for each REST method.
type API_Route_Type is new ASF.Routes.Servlets.Servlet_Route_Type with record
Descriptors : Descriptor_Array;
end record;
end ASF.Routes.Servlets.Rest;
|
-----------------------------------------------------------------------
-- asf-reoutes-servlets-rest -- Route for the REST 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.Rest;
package ASF.Routes.Servlets.Rest is
type Descriptor_Array is array (ASF.Rest.Method_Type) of ASF.Rest.Descriptor_Access;
-- The route has one descriptor for each REST method.
type API_Route_Type is new ASF.Routes.Servlets.Servlet_Route_Type with record
Descriptors : Descriptor_Array;
end record;
type API_Route_Type_Access is access all API_Route_Type'Class;
end ASF.Routes.Servlets.Rest;
|
Declare the API_Route_Type_Access type
|
Declare the API_Route_Type_Access type
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b502020383a7d9a97fec0abd5f751c84aff563d8
|
src/asf-routes-servlets.ads
|
src/asf-routes-servlets.ads
|
-----------------------------------------------------------------------
-- asf-routes-servlets -- Servlet request routing
-- 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;
with ASF.Filters;
with ASF.Servlets;
package ASF.Routes.Servlets is
type Servlet_Route_Type is new ASF.Routes.Route_Type with record
Filters : ASF.Filters.Filter_List_Access;
Servlet : ASF.Servlets.Servlet_Access;
end record;
type Servlet_Route_Type_Access is access all Servlet_Route_Type'Class;
-- Get the servlet to call for the route.
function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access;
-- Append the filter to the filter list defined by the mapping node.
procedure Append_Filter (Route : in out Servlet_Route_Type;
Filter : in ASF.Filters.Filter_Access);
-- Release the storage held by the route.
overriding
procedure Finalize (Route : in out Servlet_Route_Type);
type Proxy_Route_Type is new Servlet_Route_Type with record
Route : ASF.Routes.Route_Type_Access;
end record;
type Proxy_Route_Type_Access is access all Proxy_Route_Type'Class;
end ASF.Routes.Servlets;
|
-----------------------------------------------------------------------
-- asf-routes-servlets -- Servlet request routing
-- 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 ASF.Filters;
with ASF.Servlets;
package ASF.Routes.Servlets is
type Servlet_Route_Type is new ASF.Routes.Route_Type with record
Filters : ASF.Filters.Filter_List_Access;
Servlet : ASF.Servlets.Servlet_Access;
end record;
type Servlet_Route_Type_Access is access all Servlet_Route_Type'Class;
-- Get the servlet to call for the route.
function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access;
-- Append the filter to the filter list defined by the mapping node.
procedure Append_Filter (Route : in out Servlet_Route_Type;
Filter : in ASF.Filters.Filter_Access);
-- Release the storage held by the route.
overriding
procedure Finalize (Route : in out Servlet_Route_Type);
type Proxy_Route_Type is new Servlet_Route_Type with record
Route : ASF.Routes.Route_Type_Access;
end record;
type Proxy_Route_Type_Access is access all Proxy_Route_Type'Class;
end ASF.Routes.Servlets;
|
Remove unused with clause Ada.Finalization
|
Remove unused with clause Ada.Finalization
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
923bc6225ac19bdf72851deac4210fd62318204d
|
src/util-beans-basic-lists.adb
|
src/util-beans-basic-lists.adb
|
-----------------------------------------------------------------------
-- util-beans-basic-lists -- List bean given access to a vector
-- Copyright (C) 2011, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Basic.Lists is
-- ------------------------------
-- Initialize the list bean.
-- ------------------------------
overriding
procedure Initialize (Object : in out List_Bean) is
Bean : constant Readonly_Bean_Access := Object.Current'Unchecked_Access;
begin
Object.Row := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
function Get_Count (From : in List_Bean) return Natural is
begin
return Natural (Vectors.Length (From.List));
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is
begin
From.Current_Index := Index;
From.Current := Vectors.Element (From.List, Index - 1);
end Set_Row_Index;
-- ------------------------------
-- Returns the current row index.
-- ------------------------------
function Get_Row_Index (From : in List_Bean) return Natural is
begin
return From.Current_Index;
end Get_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (Integer (From.List.Length));
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Index);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Deletes the list bean
-- ------------------------------
procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access) is
procedure Free is
new Ada.Unchecked_Deallocation (List_Bean'Class,
List_Bean_Access);
begin
if List.all in List_Bean'Class then
declare
L : List_Bean_Access := List_Bean (List.all)'Unchecked_Access;
begin
Free (L);
List := null;
end;
end if;
end Free;
end Util.Beans.Basic.Lists;
|
-----------------------------------------------------------------------
-- util-beans-basic-lists -- List bean given access to a vector
-- Copyright (C) 2011, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Basic.Lists is
-- ------------------------------
-- Initialize the list bean.
-- ------------------------------
overriding
procedure Initialize (Object : in out List_Bean) is
Bean : constant Readonly_Bean_Access := Object.Current'Unchecked_Access;
begin
Object.Row := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
function Get_Count (From : in List_Bean) return Natural is
begin
return Natural (Vectors.Length (From.List));
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is
begin
From.Current_Index := Index;
From.Current := Vectors.Element (From.List, Index);
end Set_Row_Index;
-- ------------------------------
-- Returns the current row index.
-- ------------------------------
function Get_Row_Index (From : in List_Bean) return Natural is
begin
return From.Current_Index;
end Get_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (Integer (From.List.Length));
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Index);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Deletes the list bean
-- ------------------------------
procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access) is
procedure Free is
new Ada.Unchecked_Deallocation (List_Bean'Class,
List_Bean_Access);
begin
if List.all in List_Bean'Class then
declare
L : List_Bean_Access := List_Bean (List.all)'Unchecked_Access;
begin
Free (L);
List := null;
end;
end if;
end Free;
end Util.Beans.Basic.Lists;
|
Update the element access now that we are using positive indexes
|
Update the element access now that we are using positive indexes
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8b463f91808e733bc06ae0d4890a4aafc93cdc99
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- === Wiki Renderer ===
-- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Wiki_Syntax);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Wiki_Renderer;
Text : in Strings.WString;
Format : in Strings.WString);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer;
Doc : in Documents.Document);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
use Ada.Strings.Wide_Wide_Unbounded;
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Quote_Start, Quote_End, Quote_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
procedure Write_Optional_Space (Engine : in out Wiki_Renderer);
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer;
Optional : in Boolean := False);
procedure Need_Separator_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Wiki_Syntax := SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Need_Newline : Boolean := False;
Need_Space : Boolean := False;
Empty_Line : Boolean := True;
Empty_Previous_Line : Boolean := True;
Keep_Content : Natural := 0;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Link_First : Boolean := False;
Html_Blockquote : Boolean := False;
Line_Count : Natural := 0;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- === Wiki Renderer ===
-- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Wiki_Syntax);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Wiki_Renderer;
Text : in Strings.WString;
Format : in Strings.WString);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer;
Doc : in Documents.Document);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
use Ada.Strings.Wide_Wide_Unbounded;
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Quote_Start, Quote_End, Quote_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
procedure Write_Optional_Space (Engine : in out Wiki_Renderer);
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer;
Optional : in Boolean := False);
procedure Need_Separator_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Wiki_Syntax := SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Need_Newline : Boolean := False;
Need_Space : Boolean := False;
Empty_Line : Boolean := True;
Empty_Previous_Line : Boolean := True;
Keep_Content : Natural := 0;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Link_First : Boolean := False;
Html_Blockquote : Boolean := False;
In_Table : Boolean := False;
Col_Index : Natural := 0;
Line_Count : Natural := 0;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
-- Render the table of content.
procedure Render_TOC (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Level : in Natural);
-- Render a table component such as N_TABLE.
procedure Render_Table (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Render a table row component such as N_ROW.
procedure Render_Row (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Render a table row component such as N_COLUMN.
procedure Render_Column (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
end Wiki.Render.Wiki;
|
Add support for tables
|
Add support for tables
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5f61adb313f4200529543b0ba9c6b2b1e2a57f40
|
hal/src/hal-gpio.ads
|
hal/src/hal-gpio.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package HAL.GPIO is
type GPIO_Mode is (Unknown, Input, Output);
-- Possible modes for a GPIO point
subtype GPIO_Config_Mode is GPIO_Mode range Input .. Output;
-- Modes a GPIO point can be configured in
type GPIO_Pull_Resistor is (Floating, Pull_Up, Pull_Down);
type GPIO_Point is limited interface;
type Any_GPIO_Point is access all GPIO_Point'Class;
function Mode (This : GPIO_Point) return GPIO_Mode is abstract;
function Set_Mode (This : in out GPIO_Point;
Mode : GPIO_Config_Mode) return Boolean is abstract;
-- Return False if the mode is not available
function Pull_Resistor (This : GPIO_Point)
return GPIO_Pull_Resistor is abstract;
function Set_Pull_Resistor (This : in out GPIO_Point;
Pull : GPIO_Pull_Resistor)
return Boolean is abstract;
-- Return False if pull is not available for this GPIO point
function Set (This : GPIO_Point) return Boolean is abstract
with Pre'Class => This.Mode = Input;
procedure Set (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
procedure Clear (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
procedure Toggle (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
end HAL.GPIO;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package HAL.GPIO is
type GPIO_Mode is (Unknown, Input, Output);
-- Possible modes for a GPIO point. Unknown means that the point is
-- configured in a mode that is not described in this interface. For
-- instance alternate function mode on an STM32 micro-controller.
subtype GPIO_Config_Mode is GPIO_Mode range Input .. Output;
-- Modes a GPIO point can be configured in
type GPIO_Pull_Resistor is (Floating, Pull_Up, Pull_Down);
type GPIO_Point is limited interface;
type Any_GPIO_Point is access all GPIO_Point'Class;
function Mode (This : GPIO_Point) return GPIO_Mode is abstract;
function Set_Mode (This : in out GPIO_Point;
Mode : GPIO_Config_Mode) return Boolean is abstract;
-- Return False if the mode is not available
function Pull_Resistor (This : GPIO_Point)
return GPIO_Pull_Resistor is abstract;
function Set_Pull_Resistor (This : in out GPIO_Point;
Pull : GPIO_Pull_Resistor)
return Boolean is abstract;
-- Return False if pull is not available for this GPIO point
function Set (This : GPIO_Point) return Boolean is abstract;
-- Read actual state of the GPIO_Point.
--
-- So far all the GPIO supported by this library have the ability to read
-- the state even when they are configured as output.
-- For the output control procedures below, depending on configuration
-- and/or other devices conected to the IO line, these procedures may have
-- no actual effect on the line. For example trying to set the IO when
-- another device is pulling the line to low.
procedure Set (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
procedure Clear (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
procedure Toggle (This : in out GPIO_Point) is abstract
with Pre'Class => This.Mode = Output;
end HAL.GPIO;
|
Fix Set precondition and add comments
|
HAL.GPIO: Fix Set precondition and add comments
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,simonjwright/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
|
0be3a1085b64203e6c298839a862822afc2adb16
|
src/atlas-applications.adb
|
src/atlas-applications.adb
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 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 GNAT.MD5;
with Util.Log.Loggers;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (1);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- 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;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config) is
Fact : AWA.Applications.Factory.Application_Factory;
begin
App.Self := App;
App.Initialize (Config, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access);
App.Add_Filter (Name => "no-cache", Filter => App.Self.No_Cache'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Counters.Modules.NAME,
Module => App.Counter_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => App.Job_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => App.Wiki_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Previews.NAME,
URI => "wikis-preview",
Module => App.Preview_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.MD5;
with Util.Log.Loggers;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (1);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- 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;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
App.Self := App'Unchecked_Access;
App.Set_Global ("contextPath", CONTEXT_PATH);
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access);
App.Add_Filter (Name => "no-cache", Filter => App.Self.No_Cache'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Counters.Modules.NAME,
Module => App.Counter_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => App.Job_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => App.Wiki_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Previews.NAME,
URI => "wikis-preview",
Module => App.Preview_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
Remove the Initialize procedure and do the initialization in Initialize_Components
|
Remove the Initialize procedure and do the initialization in Initialize_Components
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
a8bedf8e62b28da1a5df17c16ac3e5b580343a90
|
src/ado-sessions-sources.adb
|
src/ado-sessions-sources.adb
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Connections
-- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Sessions.Sources is
use ADO.Drivers;
use type ADO.Drivers.Connections.Database_Connection_Access;
-- ------------------------------
-- Set the master data source
-- ------------------------------
procedure Set_Master (Controller : in out Replicated_DataSource;
Master : in Data_Source_Access) is
begin
Controller.Master := Master;
end Set_Master;
-- ------------------------------
-- Get the master data source
-- ------------------------------
function Get_Master (Controller : in Replicated_DataSource)
return Data_Source_Access is
begin
return Controller.Master;
end Get_Master;
-- ------------------------------
-- Set the slave data source
-- ------------------------------
procedure Set_Slave (Controller : in out Replicated_DataSource;
Slave : in Data_Source_Access) is
begin
Controller.Slave := Slave;
end Set_Slave;
-- ------------------------------
-- Get the slave data source
-- ------------------------------
function Get_Slave (Controller : in Replicated_DataSource)
return Data_Source_Access is
begin
return Controller.Slave;
end Get_Slave;
-- ------------------------------
-- Get a slave database connection
-- ------------------------------
-- function Get_Slave_Connection (Controller : in Replicated_DataSource)
-- return Connection'Class is
-- begin
-- return Controller.Slave.Get_Connection;
-- end Get_Slave_Connection;
end ADO.Sessions.Sources;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Connections
-- Copyright (C) 2010, 2011, 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Sessions.Sources is
-- ------------------------------
-- Set the master data source
-- ------------------------------
procedure Set_Master (Controller : in out Replicated_DataSource;
Master : in Data_Source_Access) is
begin
Controller.Master := Master;
end Set_Master;
-- ------------------------------
-- Get the master data source
-- ------------------------------
function Get_Master (Controller : in Replicated_DataSource)
return Data_Source_Access is
begin
return Controller.Master;
end Get_Master;
-- ------------------------------
-- Set the slave data source
-- ------------------------------
procedure Set_Slave (Controller : in out Replicated_DataSource;
Slave : in Data_Source_Access) is
begin
Controller.Slave := Slave;
end Set_Slave;
-- ------------------------------
-- Get the slave data source
-- ------------------------------
function Get_Slave (Controller : in Replicated_DataSource)
return Data_Source_Access is
begin
return Controller.Slave;
end Get_Slave;
-- ------------------------------
-- Get a slave database connection
-- ------------------------------
-- function Get_Slave_Connection (Controller : in Replicated_DataSource)
-- return Connection'Class is
-- begin
-- return Controller.Slave.Get_Connection;
-- end Get_Slave_Connection;
end ADO.Sessions.Sources;
|
Remove unecessary use clause
|
Remove unecessary use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
31d3354dfa1544e0155b0039034fdeea6d66bf62
|
src/gen-commands-plugins.adb
|
src/gen-commands-plugins.adb
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- 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.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name, Args);
use GNAT.Command_Line;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String is
begin
if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then
return Name;
else
return Ada.Strings.Unbounded.To_String (Name_Dir);
end if;
end Get_Directory_Name;
Result_Dir : constant String := Generator.Get_Result_Directory;
Name_Dir : Ada.Strings.Unbounded.Unbounded_String;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: d:") is
when ASCII.NUL => exit;
when 'd' =>
Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Kind : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir));
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Cmd.Usage (Name, Generator);
return;
end if;
if Kind /= "ada" and Kind /= "web" then
Generator.Error ("Invalid plugin type (must be 'ada' or 'web')");
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Generator.Set_Global ("pluginName", Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin-" & Kind);
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
exception
when Ada.Directories.Name_Error | Ada.Directories.Use_Error =>
Generator.Error ("Cannot create directory {0}", Path);
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] "
& "[-d DIR] NAME [ada | web]");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
Put_Line (" The plugin license is controlled by the -l option.");
Put_Line (" The plugin type is specified as the last argument which can be one of:");
New_Line;
Put_Line (" ada the plugin contains Ada code and a GNAT project is created");
Put_Line (" web the plugin contains XHTML, CSS, Javascript files only");
New_Line;
Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME");
Put_Line (" is used by default. The plugin is created in the directory:");
Put_Line (" plugins/NAME or plugins/DIR");
New_Line;
Put_Line (" For the Ada plugin, the command generates the following files"
& " in the plugin directory:");
Put_Line (" src/<project>-<plugin>.ads");
Put_Line (" src/<project>-<plugin>-<module>.ads");
Put_Line (" src/<project>-<plugin>-<module>.adb");
end Help;
end Gen.Commands.Plugins;
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name, Args);
use GNAT.Command_Line;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String is
begin
if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then
return Name;
else
return Ada.Strings.Unbounded.To_String (Name_Dir);
end if;
end Get_Directory_Name;
Result_Dir : constant String := Generator.Get_Result_Directory;
Name_Dir : Ada.Strings.Unbounded.Unbounded_String;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: d:") is
when ASCII.NUL => exit;
when 'd' =>
Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Kind : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Plugin_Dir : constant String := Get_Directory_Name (Name, Name_Dir);
Path : constant String := Util.Files.Compose (Dir, Plugin_Dir);
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Cmd.Usage (Name, Generator);
return;
end if;
if Kind /= "ada" and Kind /= "web" then
Generator.Error ("Invalid plugin type (must be 'ada' or 'web')");
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Generator.Set_Global ("pluginName", Name);
Generator.Set_Global ("pluginDir", Plugin_Dir);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin-" & Kind);
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
exception
when Ada.Directories.Name_Error | Ada.Directories.Use_Error =>
Generator.Error ("Cannot create directory {0}", Path);
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] "
& "[-d DIR] NAME [ada | web]");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
Put_Line (" The plugin license is controlled by the -l option.");
Put_Line (" The plugin type is specified as the last argument which can be one of:");
New_Line;
Put_Line (" ada the plugin contains Ada code and a GNAT project is created");
Put_Line (" web the plugin contains XHTML, CSS, Javascript files only");
New_Line;
Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME");
Put_Line (" is used by default. The plugin is created in the directory:");
Put_Line (" plugins/NAME or plugins/DIR");
New_Line;
Put_Line (" For the Ada plugin, the command generates the following files"
& " in the plugin directory:");
Put_Line (" src/<project>-<plugin>.ads");
Put_Line (" src/<project>-<plugin>-<module>.ads");
Put_Line (" src/<project>-<plugin>-<module>.adb");
end Help;
end Gen.Commands.Plugins;
|
Update the create-plugin generator to pass a #{pluginDir} variable that holds the plugin directory name
|
Update the create-plugin generator to pass a #{pluginDir} variable that holds the plugin directory name
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
f428fbe4e05c2686698f90e17a1925850be96bac
|
src/gen-model-mappings.ads
|
src/gen-model-mappings.ads
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 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.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_ENTITY_TYPE, T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
Nullable : 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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
-- Get the type name.
function Get_Type_Name (From : Mapping_Definition) return String;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 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.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
Postgresql_MAPPING : constant String := "Postgresql";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_ENTITY_TYPE, T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
Nullable : 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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
-- Get the type name.
function Get_Type_Name (From : Mapping_Definition) return String;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
Declare Postgresql_MAPPING constant
|
Declare Postgresql_MAPPING constant
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
38854f9853ef736d518183092cb9bec5a634595a
|
src/gen-model-packages.ads
|
src/gen-model-packages.ads
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query 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.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Strings.Sets;
with Gen.Model.List;
with Gen.Model.Mappings;
limited with Gen.Model.Enums;
limited with Gen.Model.Tables;
limited with Gen.Model.Queries;
limited with Gen.Model.Beans;
package Gen.Model.Packages is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Model Definition
-- ------------------------------
-- The <b>Model_Definition</b> contains the complete model from one or
-- several files. It maintains a list of Ada packages that must be generated.
type Model_Definition is new Definition with private;
type Model_Definition_Access is access all Model_Definition'Class;
-- ------------------------------
-- Package Definition
-- ------------------------------
-- The <b>Package_Definition</b> holds the tables, queries and other information
-- that must be generated for a given Ada package.
type Package_Definition is new Definition with private;
type Package_Definition_Access is access all Package_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Package_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Package_Definition);
-- Initialize the package instance
overriding
procedure Initialize (O : in out Package_Definition);
-- Find the type identified by the name.
function Find_Type (From : in Package_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Get the model which contains all the package definitions.
function Get_Model (From : in Package_Definition)
return Model_Definition_Access;
-- Returns True if the package is a pre-defined package and must not be generated.
function Is_Predefined (From : in Package_Definition) return Boolean;
-- Set the package as a pre-defined package.
procedure Set_Predefined (From : in out Package_Definition);
-- 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 : Model_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Initialize the model definition instance.
overriding
procedure Initialize (O : in out Model_Definition);
-- Returns True if the model contains at least one package.
function Has_Packages (O : in Model_Definition) return Boolean;
-- Register or find the package knowing its name
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access);
-- Register the declaration of the given enum in the model.
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class);
-- Register the declaration of the given table in the model.
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class);
-- Register the declaration of the given query in the model.
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_File_Definition'Class);
-- Register the declaration of the given bean in the model.
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class);
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String);
-- Find the type identified by the name.
function Find_Type (From : in Model_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String);
-- Get the directory name associated with the model.
function Get_Dirname (O : in Model_Definition) return String;
-- Get the directory name which contains the model.
function Get_Model_Directory (O : in Model_Definition) return 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 (Model : in out Model_Definition;
Name : in String);
-- Returns True if the generation is enabled for the given package name.
function Is_Generation_Enabled (Model : in Model_Definition;
Name : in String) return Boolean;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Model_Definition);
package Package_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Package_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Package_Cursor is Package_Map.Cursor;
-- Get the first package of the model definition.
function First (From : Model_Definition) return Package_Cursor;
-- Returns true if the package cursor contains a valid package
function Has_Element (Position : Package_Cursor) return Boolean
renames Package_Map.Has_Element;
-- Returns the package definition.
function Element (Position : Package_Cursor) return Package_Definition_Access
renames Package_Map.Element;
-- Move the iterator to the next package definition.
procedure Next (Position : in out Package_Cursor)
renames Package_Map.Next;
private
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
-- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>.
-- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table.
function Dependency_Compare (Left, Right : in Definition_Access) return Boolean;
-- Sort the tables on their dependency.
procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare);
subtype Table_List_Definition is Table_List.List_Definition;
subtype Enum_List_Definition is Table_List.List_Definition;
type List_Object is new Util.Beans.Basic.List_Bean with record
Values : Util.Beans.Objects.Vectors.Vector;
Row : Natural;
Value_Bean : Util.Beans.Objects.Object;
end record;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Object) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Object) 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 List_Object;
Name : in String) return Util.Beans.Objects.Object;
type Package_Definition is new Definition with record
-- Enums defined in the package.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- Hibernate tables
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- Custom queries
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- A list of external packages which are used (used for with clause generation).
Used_Types : aliased List_Object;
Used : Util.Beans.Objects.Object;
-- A map of all types defined in this package.
Types : Gen.Model.Mappings.Mapping_Maps.Map;
-- The base name for the package (ex: gen-model-users)
Base_Name : Unbounded_String;
-- The global model (used to resolve types from other packages).
Model : Model_Definition_Access;
-- True if the package uses Ada.Calendar.Time
Uses_Calendar_Time : Boolean := False;
-- True if the package is a pre-defined package (ie, defined by a UML profile).
Is_Predefined : Boolean := False;
end record;
type Model_Definition is new Definition with record
-- List of all enums.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- List of all tables.
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- List of all queries.
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- Map of all packages.
Packages : Package_Map.Map;
-- Directory associated with the model ('src', 'samples', 'regtests', ...).
Dir_Name : Unbounded_String;
-- Directory that contains the SQL and model files.
DB_Name : Unbounded_String;
-- When not empty, a list of packages that must be taken into account for the generation.
-- By default all packages and tables defined in the model are generated.
Gen_Packages : Util.Strings.Sets.Set;
end record;
end Gen.Model.Packages;
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query representation
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Strings.Sets;
with Gen.Model.List;
with Gen.Model.Mappings;
limited with Gen.Model.Enums;
limited with Gen.Model.Tables;
limited with Gen.Model.Queries;
limited with Gen.Model.Beans;
package Gen.Model.Packages is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Model Definition
-- ------------------------------
-- The <b>Model_Definition</b> contains the complete model from one or
-- several files. It maintains a list of Ada packages that must be generated.
type Model_Definition is new Definition with private;
type Model_Definition_Access is access all Model_Definition'Class;
-- ------------------------------
-- Package Definition
-- ------------------------------
-- The <b>Package_Definition</b> holds the tables, queries and other information
-- that must be generated for a given Ada package.
type Package_Definition is new Definition with private;
type Package_Definition_Access is access all Package_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Package_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Package_Definition);
-- Initialize the package instance
overriding
procedure Initialize (O : in out Package_Definition);
-- Find the type identified by the name.
function Find_Type (From : in Package_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Get the model which contains all the package definitions.
function Get_Model (From : in Package_Definition)
return Model_Definition_Access;
-- Returns True if the package is a pre-defined package and must not be generated.
function Is_Predefined (From : in Package_Definition) return Boolean;
-- Set the package as a pre-defined package.
procedure Set_Predefined (From : in out Package_Definition);
-- 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 : Model_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Initialize the model definition instance.
overriding
procedure Initialize (O : in out Model_Definition);
-- Returns True if the model contains at least one package.
function Has_Packages (O : in Model_Definition) return Boolean;
-- Register or find the package knowing its name
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access);
-- Register the declaration of the given enum in the model.
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class);
-- Register the declaration of the given table in the model.
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class);
-- Register the declaration of the given query in the model.
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_File_Definition'Class);
-- Register the declaration of the given bean in the model.
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class);
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String);
-- Find the type identified by the name.
function Find_Type (From : in Model_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String);
-- Get the directory name associated with the model.
function Get_Dirname (O : in Model_Definition) return String;
-- Get the directory name which contains the model.
function Get_Model_Directory (O : in Model_Definition) return 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 (Model : in out Model_Definition;
Name : in String);
-- Returns True if the generation is enabled for the given package name.
function Is_Generation_Enabled (Model : in Model_Definition;
Name : in String) return Boolean;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Model_Definition);
package Package_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Package_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Package_Cursor is Package_Map.Cursor;
-- Get the first package of the model definition.
function First (From : Model_Definition) return Package_Cursor;
-- Returns true if the package cursor contains a valid package
function Has_Element (Position : Package_Cursor) return Boolean
renames Package_Map.Has_Element;
-- Returns the package definition.
function Element (Position : Package_Cursor) return Package_Definition_Access
renames Package_Map.Element;
-- Move the iterator to the next package definition.
procedure Next (Position : in out Package_Cursor)
renames Package_Map.Next;
private
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
-- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>.
-- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table.
function Dependency_Compare (Left, Right : in Definition_Access) return Boolean;
-- Sort the tables on their dependency.
procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare);
subtype Table_List_Definition is Table_List.List_Definition;
subtype Enum_List_Definition is Table_List.List_Definition;
type List_Object is new Util.Beans.Basic.List_Bean with record
Values : Util.Beans.Objects.Vectors.Vector;
Row : Natural;
Value_Bean : Util.Beans.Objects.Object;
end record;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Object) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Object) 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 List_Object;
Name : in String) return Util.Beans.Objects.Object;
type Package_Definition is new Definition with record
-- Enums defined in the package.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- Hibernate tables
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- Custom queries
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- A list of external packages which are used (used for with clause generation).
Used_Spec_Types : aliased List_Object;
Used_Spec : Util.Beans.Objects.Object;
-- A list of external packages which are used (used for with clause generation).
Used_Body_Types : aliased List_Object;
Used_Body : Util.Beans.Objects.Object;
-- A map of all types defined in this package.
Types : Gen.Model.Mappings.Mapping_Maps.Map;
-- The base name for the package (ex: gen-model-users)
Base_Name : Unbounded_String;
-- The global model (used to resolve types from other packages).
Model : Model_Definition_Access;
-- True if the package uses Ada.Calendar.Time
Uses_Calendar_Time : Boolean := False;
-- True if the package is a pre-defined package (ie, defined by a UML profile).
Is_Predefined : Boolean := False;
end record;
type Model_Definition is new Definition with record
-- List of all enums.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- List of all tables.
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- List of all queries.
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- Map of all packages.
Packages : Package_Map.Map;
-- Directory associated with the model ('src', 'samples', 'regtests', ...).
Dir_Name : Unbounded_String;
-- Directory that contains the SQL and model files.
DB_Name : Unbounded_String;
-- When not empty, a list of packages that must be taken into account for the generation.
-- By default all packages and tables defined in the model are generated.
Gen_Packages : Util.Strings.Sets.Set;
end record;
end Gen.Model.Packages;
|
Add Used_Spec_Types and Used_Body_Types to separate the list of packages required by the specification and the body
|
Add Used_Spec_Types and Used_Body_Types to separate the list of
packages required by the specification and the body
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5395ce95f5af5b967db316f78531b2a087c1aa38
|
jack-client.adb
|
jack-client.adb
|
with C_String.Arrays;
with C_String;
with Interfaces.C;
with System.Address_To_Access_Conversions;
package body Jack.Client is
package C renames Interfaces.C;
use type C.int;
use type Port_Name_t;
use type System.Address;
use type Thin.Port_Flags_t;
use type Thin.Status_t;
--
-- Activate
--
procedure Activate
(Client : in Client_t;
Failed : out Boolean)
is
C_Return : constant C.int := Thin.Activate (System.Address (Client));
begin
Failed := C_Return /= 0;
end Activate;
--
-- Close
--
procedure Close
(Client : in Client_t;
Failed : out Boolean) is
begin
Failed := Thin.Client_Close (System.Address (Client)) /= 0;
end Close;
--
-- Compare
--
function Compare
(Left : in Client_t;
Right : in Client_t) return Boolean is
begin
return System.Address (Left) = System.Address (Right);
end Compare;
function Compare
(Left : in Port_t;
Right : in Port_t) return Boolean is
begin
return System.Address (Left) = System.Address (Right);
end Compare;
--
-- Connect
--
procedure Connect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean)
is
C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port));
C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port));
C_Result : constant C.int := Thin.Connect
(Client => System.Address (Client),
Source_Port => C_String.To_C_String (C_Source'Unchecked_Access),
Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access));
begin
Failed := C_Result /= 0;
end Connect;
--
-- Disconnect
--
procedure Disconnect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean)
is
C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port));
C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port));
C_Result : constant C.int := Thin.Disconnect
(Client => System.Address (Client),
Source_Port => C_String.To_C_String (C_Source'Unchecked_Access),
Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access));
begin
Failed := C_Result /= 0;
end Disconnect;
--
-- Get_Ports
--
procedure Get_Ports_Free (Data : System.Address);
pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free");
procedure Get_Ports
(Client : in Client_t;
Port_Name_Pattern : in String := "";
Port_Type_Pattern : in String := "";
Port_Flags : in Port_Flags_t := (others => False);
Ports : out Port_Name_Set_t)
is
Name : Port_Name_t;
Size : Natural;
C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags);
C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern);
C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern);
Address : constant C_String.Arrays.Pointer_Array_t :=
Thin.Get_Ports
(Client => System.Address (Client),
Port_Name_Pattern => C_String.To_C_String (C_Name'Unchecked_Access),
Type_Name_Pattern => C_String.To_C_String (C_Type'Unchecked_Access),
Flags => C_Flags);
begin
Size := C_String.Arrays.Size_Terminated (Address);
for Index in 0 .. Size loop
Port_Names.Set_Bounded_String
(Source => C_String.Arrays.Index_Terminated (Address, Index),
Target => Name);
Port_Name_Sets.Insert (Ports, Name);
end loop;
-- The strings returned by jack_get_ports are heap allocated.
Get_Ports_Free (System.Address (Address));
end Get_Ports;
--
-- Status, option and flag mapping.
--
type Status_Map_t is array (Status_Selector_t) of Thin.Status_t;
Status_Map : constant Status_Map_t := Status_Map_t'
(Failure => Thin.JackFailure,
Invalid_Option => Thin.JackInvalidOption,
Name_Not_Unique => Thin.JackNameNotUnique,
Server_Started => Thin.JackServerStarted,
Server_Failed => Thin.JackServerFailed,
Server_Error => Thin.JackServerError,
No_Such_Client => Thin.JackNoSuchClient,
Load_Failure => Thin.JackLoadFailure,
Init_Failure => Thin.JackInitFailure,
Shared_Memory_Failure => Thin.JackShmFailure,
Version_Error => Thin.JackVersionError);
type Options_Map_t is array (Option_Selector_t) of Thin.Options_t;
Options_Map : constant Options_Map_t := Options_Map_t'
(Do_Not_Start_Server => Thin.JackNoStartServer,
Use_Exact_Name => Thin.JackUseExactName,
Server_Name => Thin.JackServerName,
Load_Name => Thin.JackLoadName,
Load_Initialize => Thin.JackLoadInit);
type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t;
Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t'
(Port_Is_Input => Thin.JackPortIsInput,
Port_Is_Output => Thin.JackPortIsOutput,
Port_Is_Physical => Thin.JackPortIsPhysical,
Port_Can_Monitor => Thin.JackPortCanMonitor,
Port_Is_Terminal => Thin.JackPortIsTerminal);
function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is
Return_Options : Thin.Options_t := 0;
begin
for Selector in Options_t'Range loop
if Options (Selector) then
Return_Options := Return_Options or Options_Map (Selector);
end if;
end loop;
return Return_Options;
end Map_Options_To_Thin;
function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is
Return_Port_Flags : Thin.Port_Flags_t := 0;
begin
for Selector in Port_Flags_t'Range loop
if Port_Flags (Selector) then
Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector);
end if;
end loop;
return Return_Port_Flags;
end Map_Port_Flags_To_Thin;
function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is
Return_Status : Thin.Status_t := 0;
begin
for Selector in Status_t'Range loop
if Status (Selector) then
Return_Status := Return_Status or Status_Map (Selector);
end if;
end loop;
return Return_Status;
end Map_Status_To_Thin;
function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is
Return_Options : Options_t := (others => False);
begin
for Selector in Options_t'Range loop
Return_Options (Selector) :=
(Options and Options_Map (Selector)) = Options_Map (Selector);
end loop;
return Return_Options;
end Map_Thin_To_Options;
function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is
Return_Port_Flags : Port_Flags_t := (others => False);
begin
for Selector in Port_Flags_t'Range loop
Return_Port_Flags (Selector) :=
(Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector);
end loop;
return Return_Port_Flags;
end Map_Thin_To_Port_Flags;
function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is
Return_Status : Status_t := (others => False);
begin
for Selector in Status_t'Range loop
Return_Status (Selector) :=
(Status and Status_Map (Selector)) = Status_Map (Selector);
end loop;
return Return_Status;
end Map_Thin_To_Status;
--
-- Open
--
procedure Open
(Client_Name : in String;
Options : in Options_t;
Client : out Client_t;
Status : in out Status_t)
is
function C_Client_Open
(Client_Name : C_String.String_Not_Null_Ptr_t;
Options : Thin.Options_t;
Status : System.Address) return System.Address;
pragma Import (C, C_Client_Open, "jack_ada_client_open");
C_Client : System.Address;
C_Name : aliased C.char_array := C.To_C (Client_Name);
C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options);
C_Status : aliased Thin.Status_t := 0;
begin
pragma Assert (Client_Name /= "");
C_Client := C_Client_Open
(Client_Name => C_String.To_C_String (C_Name'Unchecked_Access),
Options => C_Options,
Status => C_Status'Address);
Status := Map_Thin_To_Status (C_Status);
if C_Client = System.Null_Address then
Client := Invalid_Client;
else
Client := Client_t (C_Client);
end if;
end Open;
--
-- Port_Register
--
procedure Port_Register
(Client : in Client_t;
Port : out Port_t;
Port_Name : in Port_Name_t;
Port_Type : in String := Default_Audio_Type;
Port_Flags : in Port_Flags_t := (others => False);
Buffer_Size : in Natural := 0)
is
C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags);
C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name));
C_Port : System.Address;
C_Type : aliased C.char_array := C.To_C (Port_Type);
Ptr_Name : C_String.String_Ptr_t;
Ptr_Type : C_String.String_Ptr_t;
begin
if Port_Name /= Port_Names.Null_Bounded_String then
Ptr_Name := C_String.To_C_String (C_Name'Unchecked_Access);
end if;
if Port_Type /= "" then
Ptr_Type := C_String.To_C_String (C_Type'Unchecked_Access);
end if;
C_Port := Thin.Port_Register
(Client => System.Address (Client),
Port_Name => Ptr_Name,
Port_Type => Ptr_Type,
Flags => C_Flags,
Buffer_Size => C.unsigned_long (Buffer_Size));
if C_Port = System.Null_Address then
Port := Invalid_Port;
else
Port := Port_t (C_Port);
end if;
end Port_Register;
--
-- Generic_Callbacks
--
package body Generic_Callbacks is
package Convert_Process is new
System.Address_To_Access_Conversions (Process_Callback_State_t);
function C_Set_Process_Callback
(Client : System.Address;
Callback : access procedure
(Number_Of_Frames : Thin.Number_Of_Frames_t;
Data : System.Address);
Data : System.Address) return Thin.Integer_t;
pragma Import (C, C_Set_Process_Callback, "jack_set_process_callback");
procedure Process_Callback_Inner
(Number_Of_Frames : Thin.Number_Of_Frames_t;
Data : System.Address)
is
State : Process_Callback_State_t;
for State'Address use Data;
begin
State.Callback
(Number_Of_Frames => Number_Of_Frames_t (Number_Of_Frames),
User_Data => State.User_Data);
end Process_Callback_Inner;
procedure Set_Process_Callback
(Client : in Client_t;
State : in Process_Callback_State_Access_t;
Failed : out Boolean)
is
Pointer : constant Convert_Process.Object_Pointer :=
Convert_Process.Object_Pointer (State);
begin
Failed := 0 /= C_Set_Process_Callback
(Client => System.Address (Client),
Callback => Process_Callback_Inner'Access,
Data => Convert_Process.To_Address (Pointer));
end Set_Process_Callback;
end Generic_Callbacks;
--
-- To_Address
--
function To_Address (Client : in Client_t) return System.Address is
begin
return System.Address (Client);
end To_Address;
function To_Address (Port : in Port_t) return System.Address is
begin
return System.Address (Port);
end To_Address;
end Jack.Client;
|
with C_String.Arrays;
with C_String;
with Interfaces.C;
with System.Address_To_Access_Conversions;
package body Jack.Client is
package C renames Interfaces.C;
use type C.int;
use type Port_Name_t;
use type System.Address;
use type Thin.Port_Flags_t;
use type Thin.Status_t;
--
-- Activate
--
procedure Activate
(Client : in Client_t;
Failed : out Boolean)
is
C_Return : constant C.int := Thin.Activate (System.Address (Client));
begin
Failed := C_Return /= 0;
end Activate;
--
-- Close
--
procedure Close
(Client : in Client_t;
Failed : out Boolean) is
begin
Failed := Thin.Client_Close (System.Address (Client)) /= 0;
end Close;
--
-- Compare
--
function Compare
(Left : in Client_t;
Right : in Client_t) return Boolean is
begin
return System.Address (Left) = System.Address (Right);
end Compare;
function Compare
(Left : in Port_t;
Right : in Port_t) return Boolean is
begin
return System.Address (Left) = System.Address (Right);
end Compare;
--
-- Connect
--
procedure Connect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean)
is
C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port));
C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port));
C_Result : constant C.int := Thin.Connect
(Client => System.Address (Client),
Source_Port => C_String.To_C_String (C_Source'Unchecked_Access),
Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access));
begin
Failed := C_Result /= 0;
end Connect;
--
-- Disconnect
--
procedure Disconnect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean)
is
C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port));
C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port));
C_Result : constant C.int := Thin.Disconnect
(Client => System.Address (Client),
Source_Port => C_String.To_C_String (C_Source'Unchecked_Access),
Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access));
begin
Failed := C_Result /= 0;
end Disconnect;
--
-- Get_Ports
--
procedure Get_Ports_Free (Data : System.Address);
pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free");
procedure Get_Ports
(Client : in Client_t;
Port_Name_Pattern : in String := "";
Port_Type_Pattern : in String := "";
Port_Flags : in Port_Flags_t := (others => False);
Ports : out Port_Name_Set_t)
is
Name : Port_Name_t;
Size : Natural;
C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags);
C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern);
C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern);
Ptr_Name : C_String.String_Ptr_t;
Ptr_Type : C_String.String_Ptr_t;
Address : C_String.Arrays.Pointer_Array_t;
begin
if Port_Name_Pattern /= Port_Names.Null_Bounded_String then
Ptr_Name := C_String.To_C_String (C_Name'Unchecked_Access);
end if;
if Port_Type_Pattern /= "" then
Ptr_Type := C_String.To_C_String (C_Type'Unchecked_Access);
end if;
Address := Thin.Get_Ports
(Client => System.Address (Client),
Port_Name_Pattern => Ptr_Name,
Type_Name_Pattern => Ptr_Type,
Flags => C_Flags);
Size := C_String.Arrays.Size_Terminated (Address);
for Index in 0 .. Size loop
Port_Names.Set_Bounded_String
(Source => C_String.Arrays.Index_Terminated (Address, Index),
Target => Name);
Port_Name_Sets.Insert (Ports, Name);
end loop;
-- The strings returned by jack_get_ports are heap allocated.
Get_Ports_Free (System.Address (Address));
end Get_Ports;
--
-- Status, option and flag mapping.
--
type Status_Map_t is array (Status_Selector_t) of Thin.Status_t;
Status_Map : constant Status_Map_t := Status_Map_t'
(Failure => Thin.JackFailure,
Invalid_Option => Thin.JackInvalidOption,
Name_Not_Unique => Thin.JackNameNotUnique,
Server_Started => Thin.JackServerStarted,
Server_Failed => Thin.JackServerFailed,
Server_Error => Thin.JackServerError,
No_Such_Client => Thin.JackNoSuchClient,
Load_Failure => Thin.JackLoadFailure,
Init_Failure => Thin.JackInitFailure,
Shared_Memory_Failure => Thin.JackShmFailure,
Version_Error => Thin.JackVersionError);
type Options_Map_t is array (Option_Selector_t) of Thin.Options_t;
Options_Map : constant Options_Map_t := Options_Map_t'
(Do_Not_Start_Server => Thin.JackNoStartServer,
Use_Exact_Name => Thin.JackUseExactName,
Server_Name => Thin.JackServerName,
Load_Name => Thin.JackLoadName,
Load_Initialize => Thin.JackLoadInit);
type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t;
Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t'
(Port_Is_Input => Thin.JackPortIsInput,
Port_Is_Output => Thin.JackPortIsOutput,
Port_Is_Physical => Thin.JackPortIsPhysical,
Port_Can_Monitor => Thin.JackPortCanMonitor,
Port_Is_Terminal => Thin.JackPortIsTerminal);
function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is
Return_Options : Thin.Options_t := 0;
begin
for Selector in Options_t'Range loop
if Options (Selector) then
Return_Options := Return_Options or Options_Map (Selector);
end if;
end loop;
return Return_Options;
end Map_Options_To_Thin;
function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is
Return_Port_Flags : Thin.Port_Flags_t := 0;
begin
for Selector in Port_Flags_t'Range loop
if Port_Flags (Selector) then
Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector);
end if;
end loop;
return Return_Port_Flags;
end Map_Port_Flags_To_Thin;
function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is
Return_Status : Thin.Status_t := 0;
begin
for Selector in Status_t'Range loop
if Status (Selector) then
Return_Status := Return_Status or Status_Map (Selector);
end if;
end loop;
return Return_Status;
end Map_Status_To_Thin;
function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is
Return_Options : Options_t := (others => False);
begin
for Selector in Options_t'Range loop
Return_Options (Selector) :=
(Options and Options_Map (Selector)) = Options_Map (Selector);
end loop;
return Return_Options;
end Map_Thin_To_Options;
function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is
Return_Port_Flags : Port_Flags_t := (others => False);
begin
for Selector in Port_Flags_t'Range loop
Return_Port_Flags (Selector) :=
(Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector);
end loop;
return Return_Port_Flags;
end Map_Thin_To_Port_Flags;
function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is
Return_Status : Status_t := (others => False);
begin
for Selector in Status_t'Range loop
Return_Status (Selector) :=
(Status and Status_Map (Selector)) = Status_Map (Selector);
end loop;
return Return_Status;
end Map_Thin_To_Status;
--
-- Open
--
procedure Open
(Client_Name : in String;
Options : in Options_t;
Client : out Client_t;
Status : in out Status_t)
is
function C_Client_Open
(Client_Name : C_String.String_Not_Null_Ptr_t;
Options : Thin.Options_t;
Status : System.Address) return System.Address;
pragma Import (C, C_Client_Open, "jack_ada_client_open");
C_Client : System.Address;
C_Name : aliased C.char_array := C.To_C (Client_Name);
C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options);
C_Status : aliased Thin.Status_t := 0;
begin
pragma Assert (Client_Name /= "");
C_Client := C_Client_Open
(Client_Name => C_String.To_C_String (C_Name'Unchecked_Access),
Options => C_Options,
Status => C_Status'Address);
Status := Map_Thin_To_Status (C_Status);
if C_Client = System.Null_Address then
Client := Invalid_Client;
else
Client := Client_t (C_Client);
end if;
end Open;
--
-- Port_Register
--
procedure Port_Register
(Client : in Client_t;
Port : out Port_t;
Port_Name : in Port_Name_t;
Port_Type : in String := Default_Audio_Type;
Port_Flags : in Port_Flags_t := (others => False);
Buffer_Size : in Natural := 0)
is
C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags);
C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name));
C_Port : System.Address;
C_Type : aliased C.char_array := C.To_C (Port_Type);
begin
C_Port := Thin.Port_Register
(Client => System.Address (Client),
Port_Name => C_String.To_C_String (C_Name'Unchecked_Access),
Port_Type => C_String.To_C_String (C_Type'Unchecked_Access),
Flags => C_Flags,
Buffer_Size => C.unsigned_long (Buffer_Size));
if C_Port = System.Null_Address then
Port := Invalid_Port;
else
Port := Port_t (C_Port);
end if;
end Port_Register;
--
-- Generic_Callbacks
--
package body Generic_Callbacks is
package Convert_Process is new
System.Address_To_Access_Conversions (Process_Callback_State_t);
function C_Set_Process_Callback
(Client : System.Address;
Callback : access procedure
(Number_Of_Frames : Thin.Number_Of_Frames_t;
Data : System.Address);
Data : System.Address) return Thin.Integer_t;
pragma Import (C, C_Set_Process_Callback, "jack_set_process_callback");
procedure Process_Callback_Inner
(Number_Of_Frames : Thin.Number_Of_Frames_t;
Data : System.Address)
is
State : Process_Callback_State_t;
for State'Address use Data;
begin
State.Callback
(Number_Of_Frames => Number_Of_Frames_t (Number_Of_Frames),
User_Data => State.User_Data);
end Process_Callback_Inner;
procedure Set_Process_Callback
(Client : in Client_t;
State : in Process_Callback_State_Access_t;
Failed : out Boolean)
is
Pointer : constant Convert_Process.Object_Pointer :=
Convert_Process.Object_Pointer (State);
begin
Failed := 0 /= C_Set_Process_Callback
(Client => System.Address (Client),
Callback => Process_Callback_Inner'Access,
Data => Convert_Process.To_Address (Pointer));
end Set_Process_Callback;
end Generic_Callbacks;
--
-- To_Address
--
function To_Address (Client : in Client_t) return System.Address is
begin
return System.Address (Client);
end To_Address;
function To_Address (Port : in Port_t) return System.Address is
begin
return System.Address (Port);
end To_Address;
end Jack.Client;
|
Fix default values
|
Fix default values
|
Ada
|
isc
|
io7m/coreland-jack-ada,io7m/coreland-jack-ada
|
5358ebbcea2ab1b91f4a041b3a8b967c39aa0a58
|
src/gen-commands-database.adb
|
src/gen-commands-database.adb
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with GNAT.Expect;
with GNAT.OS_Lib;
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with ADO.Drivers.Connections;
with ADO.Sessions.Factory;
with ADO.Statements;
with ADO.Queries;
with ADO.Parameters;
with System;
with Gen.Database.Model;
package body Gen.Commands.Database is
use GNAT.Command_Line;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database");
-- Check if the database with the given name exists.
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Check if the database with the given name has some tables.
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Expect filter to print the command output/error
procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class;
Data : in String;
Closure : in System.Address);
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
procedure Execute_Command (Name : in String;
Args : in GNAT.OS_Lib.Argument_List;
Input : in String);
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler);
-- Create the database identified by the given name.
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String);
-- Create the user and grant him access to the database.
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String);
-- ------------------------------
-- Check if the database with the given name exists.
-- ------------------------------
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Database_List);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
D : constant String := Stmt.Get_String (0);
begin
if Name = D then
return True;
end if;
end;
Stmt.Next;
end loop;
return False;
end Has_Database;
-- ------------------------------
-- Check if the database with the given name has some tables.
-- ------------------------------
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Table_List);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
return Stmt.Has_Elements;
end Has_Tables;
-- ------------------------------
-- Create the database identified by the given name.
-- ------------------------------
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Creating database '{0}'", Name);
Query.Set_Query (Gen.Database.Model.Query_Create_Database);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
end Create_Database;
-- ------------------------------
-- Create the user and grant him access to the database.
-- ------------------------------
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name);
if Password'Length > 0 then
Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password);
else
Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password);
end if;
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Bind_Param ("user", ADO.Parameters.Token (User));
if Password'Length > 0 then
Stmt.Bind_Param ("password", Password);
end if;
Stmt.Execute;
Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
end Create_User_Grant;
-- ------------------------------
-- Expect filter to print the command output/error
-- ------------------------------
procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class;
Data : in String;
Closure : in System.Address) is
pragma Unreferenced (Descriptor, Closure);
begin
Log.Error ("{0}", Data);
end Command_Output;
-- ------------------------------
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
-- ------------------------------
procedure Execute_Command (Name : in String;
Args : in GNAT.OS_Lib.Argument_List;
Input : in String) is
Proc : GNAT.Expect.Process_Descriptor;
Status : Integer;
Func : constant GNAT.Expect.Filter_Function := Command_Output'Access;
Result : GNAT.Expect.Expect_Match;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Files.Read_File (Path => Input, Into => Content);
GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc,
Command => Name,
Args => Args,
Buffer_Size => 4096,
Err_To_Out => True);
GNAT.Expect.Add_Filter (Descriptor => Proc,
Filter => Func,
Filter_On => GNAT.Expect.Output);
GNAT.Expect.Send (Descriptor => Proc,
Str => Ada.Strings.Unbounded.To_String (Content),
Add_LF => False,
Empty_Buffer => False);
GNAT.Expect.Expect (Proc, Result, ".*");
GNAT.Expect.Close (Descriptor => Proc,
Status => Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
else
Log.Error ("Error while creating the database schema.");
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read {0}", Input);
end Execute_Command;
-- ------------------------------
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
-- ------------------------------
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler) is
Database : constant String := Config.Get_Database;
Username : constant String := Config.Get_Property ("user");
Password : constant String := Config.Get_Property ("password");
Dir : constant String := Util.Files.Compose (Model, "mysql");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql");
begin
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Password'Length > 0 then
declare
Args : GNAT.OS_Lib.Argument_List (1 .. 3);
begin
Args (1) := new String '("--user=" & Username);
Args (2) := new String '("--password=" & Password);
Args (3) := new String '(Database);
Execute_Command ("mysql", Args, File);
end;
else
declare
Args : GNAT.OS_Lib.Argument_List (1 .. 2);
begin
Args (1) := new String '("--user=" & Username);
Args (2) := new String '(Database);
Execute_Command ("mysql", Args, File);
end;
end if;
end Create_Mysql_Tables;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Strings.Unbounded;
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String);
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String) is
Factory : ADO.Sessions.Factory.Session_Factory;
Root_Connection : Unbounded_String;
Pos : Natural;
begin
-- Build a connection string to create the database.
Pos := Util.Strings.Index (Database, ':');
Append (Root_Connection, Database (Database'First .. Pos));
Append (Root_Connection, "//");
Append (Root_Connection, Config.Get_Server);
if Config.Get_Port > 0 then
Append (Root_Connection, ':');
Append (Root_Connection, Util.Strings.Image (Config.Get_Port));
end if;
Append (Root_Connection, "/?user=");
Append (Root_Connection, Username);
if Password'Length > 0 then
Append (Root_Connection, "&password=");
Append (Root_Connection, Password);
end if;
Log.Info ("Connecting to {0} for database setup", Root_Connection);
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Factory.Create (To_String (Root_Connection));
declare
Name : constant String := Generator.Get_Project_Name;
DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
-- Create the database only if it does not already exists.
if not Has_Database (DB, Config.Get_Database) then
Create_Database (DB, Config.Get_Database);
end if;
-- If some tables exist, don't try to create tables again.
-- We could improve by reading the current database schema, comparing with our
-- schema and create what is missing (new tables, new columns).
if Has_Tables (DB, Config.Get_Database) then
Generator.Error ("The database {0} exists", Config.Get_Database);
else
-- Create the user grant. On MySQL, it is safe to do this several times.
Create_User_Grant (DB, Config.Get_Database,
Config.Get_Property ("user"),
Config.Get_Property ("password"));
-- And now create the tables by using the SQL script generated by Dyanmo.
Create_Mysql_Tables (Name, Model, Config, Generator);
end if;
end;
end Create_MySQL_Database;
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String) is
Config : ADO.Drivers.Connections.Configuration;
begin
Config.Set_Connection (Database);
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
if Config.Get_Driver = "mysql" then
Create_MySQL_Database (Model, Config, Database, Username, Password);
else
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
end if;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := Get_Argument;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with GNAT.Expect;
with GNAT.OS_Lib;
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with ADO.Drivers.Connections;
with ADO.Sessions.Factory;
with ADO.Statements;
with ADO.Queries;
with ADO.Parameters;
with System;
with Gen.Database.Model;
package body Gen.Commands.Database is
use GNAT.Command_Line;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database");
-- Check if the database with the given name exists.
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Check if the database with the given name has some tables.
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Expect filter to print the command output/error
procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class;
Data : in String;
Closure : in System.Address);
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
procedure Execute_Command (Name : in String;
Args : in GNAT.OS_Lib.Argument_List;
Input : in String);
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler);
-- Create the database identified by the given name.
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String);
-- Create the user and grant him access to the database.
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String);
-- ------------------------------
-- Check if the database with the given name exists.
-- ------------------------------
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Database_List);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
D : constant String := Stmt.Get_String (0);
begin
if Name = D then
return True;
end if;
end;
Stmt.Next;
end loop;
return False;
end Has_Database;
-- ------------------------------
-- Check if the database with the given name has some tables.
-- ------------------------------
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Table_List);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
return Stmt.Has_Elements;
end Has_Tables;
-- ------------------------------
-- Create the database identified by the given name.
-- ------------------------------
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Creating database '{0}'", Name);
Query.Set_Query (Gen.Database.Model.Query_Create_Database);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
end Create_Database;
-- ------------------------------
-- Create the user and grant him access to the database.
-- ------------------------------
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name);
if Password'Length > 0 then
Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password);
else
Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password);
end if;
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Bind_Param ("user", ADO.Parameters.Token (User));
if Password'Length > 0 then
Stmt.Bind_Param ("password", Password);
end if;
Stmt.Execute;
Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
end Create_User_Grant;
-- ------------------------------
-- Expect filter to print the command output/error
-- ------------------------------
procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class;
Data : in String;
Closure : in System.Address) is
pragma Unreferenced (Descriptor, Closure);
begin
Log.Error ("{0}", Data);
end Command_Output;
-- ------------------------------
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
-- ------------------------------
procedure Execute_Command (Name : in String;
Args : in GNAT.OS_Lib.Argument_List;
Input : in String) is
Proc : GNAT.Expect.Process_Descriptor;
Status : Integer;
Func : constant GNAT.Expect.Filter_Function := Command_Output'Access;
Result : GNAT.Expect.Expect_Match;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Files.Read_File (Path => Input, Into => Content);
GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc,
Command => Name,
Args => Args,
Buffer_Size => 4096,
Err_To_Out => True);
GNAT.Expect.Add_Filter (Descriptor => Proc,
Filter => Func,
Filter_On => GNAT.Expect.Output);
GNAT.Expect.Send (Descriptor => Proc,
Str => Ada.Strings.Unbounded.To_String (Content),
Add_LF => False,
Empty_Buffer => False);
GNAT.Expect.Expect (Proc, Result, ".*");
GNAT.Expect.Close (Descriptor => Proc,
Status => Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
else
Log.Error ("Error while creating the database schema.");
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read {0}", Input);
end Execute_Command;
-- ------------------------------
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
-- ------------------------------
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler) is
Database : constant String := Config.Get_Database;
Username : constant String := Config.Get_Property ("user");
Password : constant String := Config.Get_Property ("password");
Dir : constant String := Util.Files.Compose (Model, "mysql");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql");
begin
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Password'Length > 0 then
declare
Args : GNAT.OS_Lib.Argument_List (1 .. 3);
begin
Args (1) := new String '("--user=" & Username);
Args (2) := new String '("--password=" & Password);
Args (3) := new String '(Database);
Execute_Command ("mysql", Args, File);
end;
else
declare
Args : GNAT.OS_Lib.Argument_List (1 .. 2);
begin
Args (1) := new String '("--user=" & Username);
Args (2) := new String '(Database);
Execute_Command ("mysql", Args, File);
end;
end if;
end Create_Mysql_Tables;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Strings.Unbounded;
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String);
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String);
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String) is
Factory : ADO.Sessions.Factory.Session_Factory;
Root_Connection : Unbounded_String;
Pos : Natural;
begin
-- Build a connection string to create the database.
Pos := Util.Strings.Index (Database, ':');
Append (Root_Connection, Database (Database'First .. Pos));
Append (Root_Connection, "//");
Append (Root_Connection, Config.Get_Server);
if Config.Get_Port > 0 then
Append (Root_Connection, ':');
Append (Root_Connection, Util.Strings.Image (Config.Get_Port));
end if;
Append (Root_Connection, "/?user=");
Append (Root_Connection, Username);
if Password'Length > 0 then
Append (Root_Connection, "&password=");
Append (Root_Connection, Password);
end if;
Log.Info ("Connecting to {0} for database setup", Root_Connection);
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Factory.Create (To_String (Root_Connection));
declare
Name : constant String := Generator.Get_Project_Name;
DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
-- Create the database only if it does not already exists.
if not Has_Database (DB, Config.Get_Database) then
Create_Database (DB, Config.Get_Database);
end if;
-- If some tables exist, don't try to create tables again.
-- We could improve by reading the current database schema, comparing with our
-- schema and create what is missing (new tables, new columns).
if Has_Tables (DB, Config.Get_Database) then
Generator.Error ("The database {0} exists", Config.Get_Database);
else
-- Create the user grant. On MySQL, it is safe to do this several times.
Create_User_Grant (DB, Config.Get_Database,
Config.Get_Property ("user"),
Config.Get_Property ("password"));
-- And now create the tables by using the SQL script generated by Dyanmo.
Create_Mysql_Tables (Name, Model, Config, Generator);
end if;
end;
end Create_MySQL_Database;
-- ------------------------------
-- Create the SQLite database.
-- ------------------------------
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String) is
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Config.Get_Database;
Dir : constant String := Util.Files.Compose (Model, "sqlite");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-sqlite.sql");
Args : GNAT.OS_Lib.Argument_List (1 .. 1);
begin
if Ada.Directories.Exists (Path) then
Log.Info ("Connecting to {0} for database setup", Database);
end if;
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
Args (1) := new String '(Path);
Execute_Command ("sqlite3", Args, File);
end Create_SQLite_Database;
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String) is
Config : ADO.Drivers.Connections.Configuration;
begin
Config.Set_Connection (Database);
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
if Config.Get_Driver = "mysql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Create_MySQL_Database (Model, Config, Database, Username, Password);
elsif Config.Get_Driver = "sqlite" then
Create_SQLite_Database (Model, Config, Database);
else
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
end if;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := Get_Argument;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
Define and implement the Create_SQLite_Database procedure to configure a SQLite database
|
Define and implement the Create_SQLite_Database procedure to configure a SQLite database
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5b6c720287a5507c666e67a5c3548879522559a8
|
samples/render.adb
|
samples/render.adb
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Objects;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use EL.Objects;
Factory : ASF.Applications.Main.Application_Factory;
App : Applications.Main.Application;
Conf : Applications.Config;
begin
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
App.Initialize (Conf, Factory);
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
if Pos > 0 then
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (Value (Pos + 1 .. Value'Last)));
else
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (True));
end if;
end;
when others =>
exit;
end case;
end loop;
declare
View_Name : constant String := Get_Argument;
Pos : constant Natural := Index (View_Name, ".");
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
if View_Name = "" or Pos = 0 then
Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file");
Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml");
return;
end if;
Req.Set_Path_Info (View_Name (View_Name'First .. Pos - 1));
App.Dispatch (Page => View_Name (View_Name'First .. Pos - 1),
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Objects;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use EL.Objects;
Factory : ASF.Applications.Main.Application_Factory;
App : Applications.Main.Application;
Conf : Applications.Config;
begin
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
Conf.Set ("view.dir", ".");
Conf.Set ("view.file_ext", "");
App.Initialize (Conf, Factory);
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
if Pos > 0 then
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (Value (Pos + 1 .. Value'Last)));
else
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (True));
end if;
end;
when others =>
exit;
end case;
end loop;
declare
View_Name : constant String := Get_Argument;
Pos : constant Natural := Index (View_Name, ".");
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
if View_Name = "" or Pos = 0 then
Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file");
Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml");
return;
end if;
Req.Set_Method ("GET");
Req.Set_Request_URI (View_Name (View_Name'First .. Pos - 1));
App.Dispatch (Page => View_Name (View_Name'First .. Pos - 1),
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
Fix the render example
|
Fix the render example
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2211abd84c686f81934f2ad9391c17183efcba0f
|
src/util-systems.ads
|
src/util-systems.ads
|
-----------------------------------------------------------------------
-- util-systems -- System specific utilities
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Systems is
pragma Preelaborate;
end Util.Systems;
|
-----------------------------------------------------------------------
-- util-systems -- System specific utilities
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Systems is
pragma Pure;
end Util.Systems;
|
Make this package Pure
|
Make this package Pure
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
66e650b86d2151951e6a845c8a11e1b4aff0ccf6
|
1-base/lace/source/text/lace-text-forge.adb
|
1-base/lace/source/text/lace-text-forge.adb
|
with
ada.Characters.latin_1,
ada.Strings.unbounded,
ada.Text_IO;
package body lace.Text.forge
is
--------
-- Files
--
function to_String (Filename : in forge.Filename) return String
is
use ada.Strings.unbounded,
ada.Text_IO;
the_File : ada.Text_IO.File_type;
Pad : unbounded_String;
begin
open (the_File, in_File, String (Filename));
while not end_of_File (the_File)
loop
declare
use ada.Characters;
Line : constant String := get_Line (the_File);
begin
if Line (Line'Last) = latin_1.CR
then
append (Pad, Line (Line'First .. Line'Last - 1) & latin_1.LF);
else
append (Pad, Line & latin_1.LF);
end if;
end;
end loop;
close (the_File);
return to_String (Pad);
end to_String;
function to_Text (Filename : in forge.Filename) return Item
is
begin
return to_Text (to_String (Filename));
end to_Text;
procedure store (Filename : in forge.Filename; the_String : in String)
is
use ada.Text_IO;
File : File_type;
begin
create (File, out_File, String (Filename));
put (File, the_String);
close (File);
end store;
--------------
-- Stock Items
--
function to_Text_2 (From : in String) return Item_2
is
begin
return to_Text (From, capacity => 2);
end to_Text_2;
function to_Text_2 (From : in Text.item) return Item_2
is
begin
return to_Text (to_String (From), capacity => 2);
end to_Text_2;
function to_Text_4 (From : in String) return Item_4
is
begin
return to_Text (From, capacity => 4);
end to_Text_4;
function to_Text_4 (From : in Text.item) return Item_4
is
begin
return to_Text (to_String (From), capacity => 4);
end to_Text_4;
function to_Text_8 (From : in String) return Item_8
is
begin
return to_Text (From, capacity => 8);
end to_Text_8;
function to_Text_8 (From : in Text.item) return Item_8
is
begin
return to_Text (to_String (From), capacity => 8);
end to_Text_8;
function to_Text_16 (From : in String) return Item_16
is
begin
return to_Text (From, capacity => 16);
end to_Text_16;
function to_Text_16 (From : in Text.item) return Item_16
is
begin
return to_Text (to_String (From), capacity => 16);
end to_Text_16;
function to_Text_32 (From : in String) return Item_32
is
begin
return to_Text (From, capacity => 32);
end to_Text_32;
function to_Text_32 (From : in Text.item) return Item_32
is
begin
return to_Text (to_String (From), capacity => 32);
end to_Text_32;
function to_Text_64 (From : in String) return Item_64
is
begin
return to_Text (From, capacity => 64);
end to_Text_64;
function to_Text_64 (From : in Text.item) return Item_64
is
begin
return to_Text (to_String (From), capacity => 64);
end to_Text_64;
function to_Text_128 (From : in String) return Item_128
is
begin
return to_Text (From, capacity => 128);
end to_Text_128;
function to_Text_128 (From : in Text.item) return Item_128
is
begin
return to_Text (to_String (From), capacity => 128);
end to_Text_128;
function to_Text_256 (From : in String) return Item_256
is
begin
return to_Text (From, capacity => 256);
end to_Text_256;
function to_Text_256 (From : in Text.item) return Item_256
is
begin
return to_Text (to_String (From), capacity => 256);
end to_Text_256;
function to_Text_512 (From : in String) return Item_512
is
begin
return to_Text (From, capacity => 512);
end to_Text_512;
function to_Text_512 (From : in Text.item) return Item_512
is
begin
return to_Text (to_String (From), capacity => 512);
end to_Text_512;
function to_Text_1k (From : in String) return Item_1k
is
begin
return to_Text (From, capacity => 1024);
end to_Text_1k;
function to_Text_1k (From : in Text.item) return Item_1k
is
begin
return to_Text (to_String (From), capacity => 1024);
end to_Text_1k;
function to_Text_2k (From : in String) return Item_2k
is
begin
return to_Text (From, capacity => 2 * 1024);
end to_Text_2k;
function to_Text_2k (From : in Text.item) return Item_2k
is
begin
return to_Text (to_String (From), capacity => 2 * 1024);
end to_Text_2k;
function to_Text_4k (From : in String) return Item_4k
is
begin
return to_Text (From, capacity => 4 * 1024);
end to_Text_4k;
function to_Text_4k (From : in Text.item) return Item_4k
is
begin
return to_Text (to_String (From), capacity => 4 * 1024);
end to_Text_4k;
function to_Text_8k (From : in String) return Item_8k
is
begin
return to_Text (From, capacity => 8 * 1024);
end to_Text_8k;
function to_Text_8k (From : in Text.item) return Item_8k
is
begin
return to_Text (to_String (From), capacity => 8 * 1024);
end to_Text_8k;
function to_Text_16k (From : in String) return Item_16k
is
begin
return to_Text (From, capacity => 16 * 1024);
end to_Text_16k;
function to_Text_16k (From : in Text.item) return Item_16k
is
begin
return to_Text (to_String (From), capacity => 16 * 1024);
end to_Text_16k;
function to_Text_32k (From : in String) return Item_32k
is
begin
return to_Text (From, capacity => 32 * 1024);
end to_Text_32k;
function to_Text_32k (From : in Text.item) return Item_32k
is
begin
return to_Text (to_String (From), capacity => 32 * 1024);
end to_Text_32k;
function to_Text_64k (From : in String) return Item_64k
is
begin
return to_Text (From, capacity => 64 * 1024);
end to_Text_64k;
function to_Text_64k (From : in Text.item) return Item_64k
is
begin
return to_Text (to_String (From), capacity => 64 * 1024);
end to_Text_64k;
function to_Text_128k (From : in String) return Item_128k
is
begin
return to_Text (From, capacity => 128 * 1024);
end to_Text_128k;
function to_Text_128k (From : in Text.item) return Item_128k
is
begin
return to_Text (to_String (From), capacity => 128 * 1024);
end to_Text_128k;
function to_Text_256k (From : in String) return Item_256k
is
begin
return to_Text (From, capacity => 256 * 1024);
end to_Text_256k;
function to_Text_256k (From : in Text.item) return Item_256k
is
begin
return to_Text (to_String (From), capacity => 256 * 1024);
end to_Text_256k;
function to_Text_512k (From : in String) return Item_512k
is
begin
return to_Text (From, capacity => 512 * 1024);
end to_Text_512k;
function to_Text_512k (From : in Text.item) return Item_512k
is
begin
return to_Text (to_String (From), capacity => 512 * 1024);
end to_Text_512k;
function to_Text_1m (From : in String) return Item_1m
is
begin
return to_Text (From, capacity => 1024 * 1024);
end to_Text_1m;
function to_Text_1m (From : in Text.item) return Item_1m
is
begin
return to_Text (to_String (From), capacity => 1024 * 1024);
end to_Text_1m;
function to_Text_2m (From : in String) return Item_2m
is
begin
return to_Text (From, capacity => 2 * 1024 * 1024);
end to_Text_2m;
function to_Text_2m (From : in Text.item) return Item_2m
is
begin
return to_Text (to_String (From), capacity => 2 * 1024 * 1024);
end to_Text_2m;
function to_Text_4m (From : in String) return Item_4m
is
begin
return to_Text (From, capacity => 4 * 1024 * 1024);
end to_Text_4m;
function to_Text_4m (From : in Text.item) return Item_4m
is
begin
return to_Text (to_String (From), capacity => 4 * 1024 * 1024);
end to_Text_4m;
function to_Text_8m (From : in String) return Item_8m
is
begin
return to_Text (From, capacity => 8 * 1024 * 1024);
end to_Text_8m;
function to_Text_8m (From : in Text.item) return Item_8m
is
begin
return to_Text (to_String (From), capacity => 8 * 1024 * 1024);
end to_Text_8m;
function to_Text_16m (From : in String) return Item_16m
is
begin
return to_Text (From, capacity => 16 * 1024 * 1024);
end to_Text_16m;
function to_Text_16m (From : in Text.item) return Item_16m
is
begin
return to_Text (to_String (From), capacity => 16 * 1024 * 1024);
end to_Text_16m;
function to_Text_32m (From : in String) return Item_32m
is
begin
return to_Text (From, capacity => 32 * 1024 * 1024);
end to_Text_32m;
function to_Text_32m (From : in Text.item) return Item_32m
is
begin
return to_Text (to_String (From), capacity => 32 * 1024 * 1024);
end to_Text_32m;
function to_Text_64m (From : in String) return Item_64m
is
begin
return to_Text (From, capacity => 64 * 1024 * 1024);
end to_Text_64m;
function to_Text_64m (From : in Text.item) return Item_64m
is
begin
return to_Text (to_String (From), capacity => 64 * 1024 * 1024);
end to_Text_64m;
function to_Text_128m (From : in String) return Item_128m
is
begin
return to_Text (From, capacity => 128 * 1024 * 1024);
end to_Text_128m;
function to_Text_128m (From : in Text.item) return Item_128m
is
begin
return to_Text (to_String (From), capacity => 128 * 1024 * 1024);
end to_Text_128m;
function to_Text_256m (From : in String) return Item_256m
is
begin
return to_Text (From, capacity => 256 * 1024 * 1024);
end to_Text_256m;
function to_Text_256m (From : in Text.item) return Item_256m
is
begin
return to_Text (to_String (From), capacity => 256 * 1024 * 1024);
end to_Text_256m;
function to_Text_512m (From : in String) return Item_512m
is
begin
return to_Text (From, capacity => 512 * 1024 * 1024);
end to_Text_512m;
function to_Text_512m (From : in Text.item) return Item_512m
is
begin
return to_Text (to_String (From), capacity => 512 * 1024 * 1024);
end to_Text_512m;
end lace.Text.forge;
|
with
ada.Characters.latin_1,
ada.Strings.unbounded,
ada.Text_IO;
package body lace.Text.forge
is
--------
-- Files
--
function to_String (Filename : in forge.Filename) return String
is
use ada.Strings.unbounded,
ada.Text_IO;
the_File : ada.Text_IO.File_type;
Pad : unbounded_String;
begin
open (the_File, in_File, String (Filename));
while not end_of_File (the_File)
loop
declare
use ada.Characters;
Line : constant String := get_Line (the_File);
begin
append (Pad, Line & latin_1.LF);
end;
end loop;
close (the_File);
return to_String (Pad);
end to_String;
function to_Text (Filename : in forge.Filename) return Item
is
begin
return to_Text (to_String (Filename));
end to_Text;
procedure store (Filename : in forge.Filename; the_String : in String)
is
use ada.Text_IO;
File : File_type;
begin
create (File, out_File, String (Filename));
put (File, the_String);
close (File);
end store;
--------------
-- Stock Items
--
function to_Text_2 (From : in String) return Item_2
is
begin
return to_Text (From, capacity => 2);
end to_Text_2;
function to_Text_2 (From : in Text.item) return Item_2
is
begin
return to_Text (to_String (From), capacity => 2);
end to_Text_2;
function to_Text_4 (From : in String) return Item_4
is
begin
return to_Text (From, capacity => 4);
end to_Text_4;
function to_Text_4 (From : in Text.item) return Item_4
is
begin
return to_Text (to_String (From), capacity => 4);
end to_Text_4;
function to_Text_8 (From : in String) return Item_8
is
begin
return to_Text (From, capacity => 8);
end to_Text_8;
function to_Text_8 (From : in Text.item) return Item_8
is
begin
return to_Text (to_String (From), capacity => 8);
end to_Text_8;
function to_Text_16 (From : in String) return Item_16
is
begin
return to_Text (From, capacity => 16);
end to_Text_16;
function to_Text_16 (From : in Text.item) return Item_16
is
begin
return to_Text (to_String (From), capacity => 16);
end to_Text_16;
function to_Text_32 (From : in String) return Item_32
is
begin
return to_Text (From, capacity => 32);
end to_Text_32;
function to_Text_32 (From : in Text.item) return Item_32
is
begin
return to_Text (to_String (From), capacity => 32);
end to_Text_32;
function to_Text_64 (From : in String) return Item_64
is
begin
return to_Text (From, capacity => 64);
end to_Text_64;
function to_Text_64 (From : in Text.item) return Item_64
is
begin
return to_Text (to_String (From), capacity => 64);
end to_Text_64;
function to_Text_128 (From : in String) return Item_128
is
begin
return to_Text (From, capacity => 128);
end to_Text_128;
function to_Text_128 (From : in Text.item) return Item_128
is
begin
return to_Text (to_String (From), capacity => 128);
end to_Text_128;
function to_Text_256 (From : in String) return Item_256
is
begin
return to_Text (From, capacity => 256);
end to_Text_256;
function to_Text_256 (From : in Text.item) return Item_256
is
begin
return to_Text (to_String (From), capacity => 256);
end to_Text_256;
function to_Text_512 (From : in String) return Item_512
is
begin
return to_Text (From, capacity => 512);
end to_Text_512;
function to_Text_512 (From : in Text.item) return Item_512
is
begin
return to_Text (to_String (From), capacity => 512);
end to_Text_512;
function to_Text_1k (From : in String) return Item_1k
is
begin
return to_Text (From, capacity => 1024);
end to_Text_1k;
function to_Text_1k (From : in Text.item) return Item_1k
is
begin
return to_Text (to_String (From), capacity => 1024);
end to_Text_1k;
function to_Text_2k (From : in String) return Item_2k
is
begin
return to_Text (From, capacity => 2 * 1024);
end to_Text_2k;
function to_Text_2k (From : in Text.item) return Item_2k
is
begin
return to_Text (to_String (From), capacity => 2 * 1024);
end to_Text_2k;
function to_Text_4k (From : in String) return Item_4k
is
begin
return to_Text (From, capacity => 4 * 1024);
end to_Text_4k;
function to_Text_4k (From : in Text.item) return Item_4k
is
begin
return to_Text (to_String (From), capacity => 4 * 1024);
end to_Text_4k;
function to_Text_8k (From : in String) return Item_8k
is
begin
return to_Text (From, capacity => 8 * 1024);
end to_Text_8k;
function to_Text_8k (From : in Text.item) return Item_8k
is
begin
return to_Text (to_String (From), capacity => 8 * 1024);
end to_Text_8k;
function to_Text_16k (From : in String) return Item_16k
is
begin
return to_Text (From, capacity => 16 * 1024);
end to_Text_16k;
function to_Text_16k (From : in Text.item) return Item_16k
is
begin
return to_Text (to_String (From), capacity => 16 * 1024);
end to_Text_16k;
function to_Text_32k (From : in String) return Item_32k
is
begin
return to_Text (From, capacity => 32 * 1024);
end to_Text_32k;
function to_Text_32k (From : in Text.item) return Item_32k
is
begin
return to_Text (to_String (From), capacity => 32 * 1024);
end to_Text_32k;
function to_Text_64k (From : in String) return Item_64k
is
begin
return to_Text (From, capacity => 64 * 1024);
end to_Text_64k;
function to_Text_64k (From : in Text.item) return Item_64k
is
begin
return to_Text (to_String (From), capacity => 64 * 1024);
end to_Text_64k;
function to_Text_128k (From : in String) return Item_128k
is
begin
return to_Text (From, capacity => 128 * 1024);
end to_Text_128k;
function to_Text_128k (From : in Text.item) return Item_128k
is
begin
return to_Text (to_String (From), capacity => 128 * 1024);
end to_Text_128k;
function to_Text_256k (From : in String) return Item_256k
is
begin
return to_Text (From, capacity => 256 * 1024);
end to_Text_256k;
function to_Text_256k (From : in Text.item) return Item_256k
is
begin
return to_Text (to_String (From), capacity => 256 * 1024);
end to_Text_256k;
function to_Text_512k (From : in String) return Item_512k
is
begin
return to_Text (From, capacity => 512 * 1024);
end to_Text_512k;
function to_Text_512k (From : in Text.item) return Item_512k
is
begin
return to_Text (to_String (From), capacity => 512 * 1024);
end to_Text_512k;
function to_Text_1m (From : in String) return Item_1m
is
begin
return to_Text (From, capacity => 1024 * 1024);
end to_Text_1m;
function to_Text_1m (From : in Text.item) return Item_1m
is
begin
return to_Text (to_String (From), capacity => 1024 * 1024);
end to_Text_1m;
function to_Text_2m (From : in String) return Item_2m
is
begin
return to_Text (From, capacity => 2 * 1024 * 1024);
end to_Text_2m;
function to_Text_2m (From : in Text.item) return Item_2m
is
begin
return to_Text (to_String (From), capacity => 2 * 1024 * 1024);
end to_Text_2m;
function to_Text_4m (From : in String) return Item_4m
is
begin
return to_Text (From, capacity => 4 * 1024 * 1024);
end to_Text_4m;
function to_Text_4m (From : in Text.item) return Item_4m
is
begin
return to_Text (to_String (From), capacity => 4 * 1024 * 1024);
end to_Text_4m;
function to_Text_8m (From : in String) return Item_8m
is
begin
return to_Text (From, capacity => 8 * 1024 * 1024);
end to_Text_8m;
function to_Text_8m (From : in Text.item) return Item_8m
is
begin
return to_Text (to_String (From), capacity => 8 * 1024 * 1024);
end to_Text_8m;
function to_Text_16m (From : in String) return Item_16m
is
begin
return to_Text (From, capacity => 16 * 1024 * 1024);
end to_Text_16m;
function to_Text_16m (From : in Text.item) return Item_16m
is
begin
return to_Text (to_String (From), capacity => 16 * 1024 * 1024);
end to_Text_16m;
function to_Text_32m (From : in String) return Item_32m
is
begin
return to_Text (From, capacity => 32 * 1024 * 1024);
end to_Text_32m;
function to_Text_32m (From : in Text.item) return Item_32m
is
begin
return to_Text (to_String (From), capacity => 32 * 1024 * 1024);
end to_Text_32m;
function to_Text_64m (From : in String) return Item_64m
is
begin
return to_Text (From, capacity => 64 * 1024 * 1024);
end to_Text_64m;
function to_Text_64m (From : in Text.item) return Item_64m
is
begin
return to_Text (to_String (From), capacity => 64 * 1024 * 1024);
end to_Text_64m;
function to_Text_128m (From : in String) return Item_128m
is
begin
return to_Text (From, capacity => 128 * 1024 * 1024);
end to_Text_128m;
function to_Text_128m (From : in Text.item) return Item_128m
is
begin
return to_Text (to_String (From), capacity => 128 * 1024 * 1024);
end to_Text_128m;
function to_Text_256m (From : in String) return Item_256m
is
begin
return to_Text (From, capacity => 256 * 1024 * 1024);
end to_Text_256m;
function to_Text_256m (From : in Text.item) return Item_256m
is
begin
return to_Text (to_String (From), capacity => 256 * 1024 * 1024);
end to_Text_256m;
function to_Text_512m (From : in String) return Item_512m
is
begin
return to_Text (From, capacity => 512 * 1024 * 1024);
end to_Text_512m;
function to_Text_512m (From : in Text.item) return Item_512m
is
begin
return to_Text (to_String (From), capacity => 512 * 1024 * 1024);
end to_Text_512m;
end lace.Text.forge;
|
Remove unneeded handling of <CR> line terminators.
|
lace.text.forge: Remove unneeded handling of <CR> line terminators.
|
Ada
|
isc
|
charlie5/lace,charlie5/lace,charlie5/lace
|
217219f906d8ddd9e67adac48e71551a658a4dc2
|
src/sys/lzma/util-streams-buffered-lzma.ads
|
src/sys/lzma/util-streams-buffered-lzma.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 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 Lzma.Base;
use Lzma;
package Util.Streams.Buffered.Lzma is
-- -----------------------
-- Compress stream
-- -----------------------
-- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to
-- compress the data before writing it to the output.
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
overriding
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Compress_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Compress_Stream);
private
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Compress_Stream);
end Util.Streams.Buffered.Lzma;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018, 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 Lzma.Base;
use Lzma;
package Util.Streams.Buffered.Lzma is
-- -----------------------
-- Compress stream
-- -----------------------
-- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to
-- compress the data before writing it to the output.
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
overriding
procedure Initialize (Stream : in out Compress_Stream;
Output : access Output_Stream'Class;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Compress_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Compress_Stream);
-- -----------------------
-- Compress stream
-- -----------------------
-- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to
-- compress the data before writing it to the output.
type Decompress_Stream is limited new Util.Streams.Buffered.Input_Buffer_Stream with private;
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
overriding
procedure Initialize (Stream : in out Decompress_Stream;
Input : access Input_Stream'Class;
Size : in Positive);
-- Write the buffer array to the output stream.
overriding
procedure Read (Stream : in out Decompress_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record
Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Compress_Stream);
type Decompress_Stream is limited new Util.Streams.Buffered.Input_Buffer_Stream with record
Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT;
Action : Base.lzma_action := Base.LZMA_RUN;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Decompress_Stream);
end Util.Streams.Buffered.Lzma;
|
Declare Decompress_Stream type and associated operations for LZMA stream decompression
|
Declare Decompress_Stream type and associated operations for LZMA stream decompression
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
44868e3c43fad4b15b6adcc20a071613188d66e9
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 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.Unchecked_Deallocation;
with ASF.Servlets.Faces;
with ASF.Servlets.Ajax;
with ASF.Responses;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
Empty : Util.Properties.Manager;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access);
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 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.Unchecked_Deallocation;
with Servlet.Core;
with ASF.Servlets.Faces;
with ASF.Servlets.Ajax;
with ASF.Responses;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
Empty : Util.Properties.Manager;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access);
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
use type Servlet.Core.Servlet_Registry_Access;
Result : constant Servlet.Core.Servlet_Registry_Access := Servlet.Tests.Get_Application;
begin
if Result = null then
return App;
elsif Result.all in ASF.Applications.Main.Application'Class then
return ASF.Applications.Main.Application'Class (Result.all)'Access;
else
return App;
end if;
end Get_Application;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
Update Get_Application to use Servlet.Tests.Get_Application
|
Update Get_Application to use Servlet.Tests.Get_Application
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a2f3c3ac1e27dbe75d0e573c22a14ef21ab67b0b
|
matp/src/mat-expressions.adb
|
matp/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- 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;
with MAT.Frames;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
Resolver : Resolver_Type_Access;
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
Region : MAT.Memory.Region_Info;
begin
if Resolver /= null then
case Kind is
when INSIDE_REGION | INSIDE_DIRECT_REGION =>
Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name));
when others =>
Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name));
end case;
end if;
if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_IN_FUNC_DIRECT,
Min_Addr => Region.Start_Addr,
Max_Addr => Region.End_Addr);
else
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_IN_FUNC,
Min_Addr => Region.Start_Addr,
Max_Addr => Region.End_Addr);
end if;
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_HAS_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create a event type expression check.
-- ------------------------------
function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type)
return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_TYPE,
Event_Kind => Event_Kind);
return Result;
end Create_Event_Type;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Event_Id_Type;
Max : in MAT.Events.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Create an expression node to keep allocation events which don't have any associated free.
-- ------------------------------
function Create_No_Free return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NO_FREE);
return Result;
end Create_No_Free;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Target_Event_Type) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Event);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when N_IN_FUNC =>
return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr);
when N_IN_FUNC_DIRECT =>
return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr);
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Target_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Event_Id_Type;
use type MAT.Events.Probe_Index_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when N_TYPE =>
return Event.Index = Node.Event_Kind;
when N_HAS_ADDR =>
if Event.Index = MAT.Events.MSG_MALLOC
or Event.Index = MAT.Events.MSG_REALLOC
then
return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr;
end if;
return False;
when N_NO_FREE =>
if Event.Index = MAT.Events.MSG_MALLOC
or Event.Index = MAT.Events.MSG_REALLOC
then
return Event.Next_Id = 0;
else
return False;
end if;
when N_IN_FUNC =>
return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr);
when N_IN_FUNC_DIRECT =>
return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr);
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String;
Resolver : in Resolver_Type_Access) return Expression_Type is
begin
MAT.Expressions.Resolver := Resolver;
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- 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;
with MAT.Frames;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
Resolver : Resolver_Type_Access;
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
Region : MAT.Memory.Region_Info;
begin
if Resolver /= null then
case Kind is
when INSIDE_REGION | INSIDE_DIRECT_REGION =>
Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name));
when others =>
Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name));
end case;
end if;
if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_IN_FUNC_DIRECT,
Min_Addr => Region.Start_Addr,
Max_Addr => Region.End_Addr);
else
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_IN_FUNC,
Min_Addr => Region.Start_Addr,
Max_Addr => Region.End_Addr);
end if;
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_HAS_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create a event type expression check.
-- ------------------------------
function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type)
return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_TYPE,
Event_Kind => Event_Kind);
return Result;
end Create_Event_Type;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Event_Id_Type;
Max : in MAT.Events.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Create an expression node to keep allocation events which don't have any associated free.
-- ------------------------------
function Create_No_Free return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NO_FREE);
return Result;
end Create_No_Free;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Target_Event_Type) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Event);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when N_HAS_ADDR =>
return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr;
when N_IN_FUNC =>
return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr);
when N_IN_FUNC_DIRECT =>
return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr);
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Target_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Event_Id_Type;
use type MAT.Events.Probe_Index_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when N_TYPE =>
return Event.Index = Node.Event_Kind;
when N_HAS_ADDR =>
if Event.Index = MAT.Events.MSG_MALLOC
or Event.Index = MAT.Events.MSG_REALLOC
then
return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr;
end if;
return False;
when N_NO_FREE =>
if Event.Index = MAT.Events.MSG_MALLOC
or Event.Index = MAT.Events.MSG_REALLOC
then
return Event.Next_Id = 0;
else
return False;
end if;
when N_IN_FUNC =>
return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr);
when N_IN_FUNC_DIRECT =>
return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr);
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String;
Resolver : in Resolver_Type_Access) return Expression_Type is
begin
MAT.Expressions.Resolver := Resolver;
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
Add support for N_HAS_ADDR in the memory slot Is_Selected function
|
Add support for N_HAS_ADDR in the memory slot Is_Selected function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8e208aa1ad80ac90678a3d6af47d087e2fefe53d
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- 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 GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Tests;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Fact : ASF.Applications.Main.Application_Factory;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Fact);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'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 => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
Content : Unbounded_String;
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Read_Content (Content);
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in AUnit.Assertions.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in AUnit.Assertions.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- 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 GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Tests;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Fact : ASF.Applications.Main.Application_Factory;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Fact);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'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 => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
Content : Unbounded_String;
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Read_Content (Content);
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in AUnit.Assertions.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in AUnit.Assertions.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
end ASF.Tests;
|
Add the Ajax servlet
|
Add the Ajax servlet
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
1434d0406f456e5b3864a60357ecb65b24755f4c
|
src/sys/encoders/util-encoders.ads
|
src/sys/encoders/util-encoders.ads
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
-- === Encoder and Decoders ===
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects
-- which provide a mechanism to transform a stream from one format into
-- another format.
--
-- ==== Simple encoding and decoding ====
--
package Util.Encoders is
pragma Preelaborate;
use Ada.Streams;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Secret key
-- ------------------------------
-- A secret key of the given length, it cannot be copied and is safely erased.
subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last;
type Secret_Key (Length : Key_Length) is limited private;
-- Create the secret key from the password string.
function Create (Password : in String) return Secret_Key
with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length;
procedure Create (Password : in String;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
function Encode_Binary (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
function Decode_Binary (E : in Decoder;
Data : in String) return Ada.Streams.Stream_Element_Array;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Array;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Finalization;
type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record
Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0);
end record;
overriding
procedure Finalize (Object : in out Secret_Key);
-- Transform the input data into the target string.
procedure Convert (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array;
Into : out String);
type Encoder is limited new Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is limited new Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
-- === Encoder and Decoders ===
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects
-- which provide a mechanism to transform a stream from one format into
-- another format.
--
-- ==== Simple encoding and decoding ====
--
package Util.Encoders is
pragma Preelaborate;
use Ada.Streams;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Secret key
-- ------------------------------
-- A secret key of the given length, it cannot be copied and is safely erased.
subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last;
type Secret_Key (Length : Key_Length) is limited private;
-- Create the secret key from the password string.
function Create (Password : in String) return Secret_Key
with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length;
procedure Create (Password : in String;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
procedure Create (Password : in Stream_Element_Array;
Key : out Secret_Key)
with Pre => Password'Length > 0, Post => Key.Length = Password'Length;
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
function Encode_Binary (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
function Decode_Binary (E : in Decoder;
Data : in String) return Ada.Streams.Stream_Element_Array;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Array;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Finalization;
type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record
Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0);
end record;
overriding
procedure Finalize (Object : in out Secret_Key);
-- Transform the input data into the target string.
procedure Convert (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array;
Into : out String);
type Encoder is limited new Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is limited new Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
Add a Create procedure that takes a Stream_Element_Array as password
|
Add a Create procedure that takes a Stream_Element_Array as password
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
511638580447594558d7976b8c748dde3d8987a9
|
src/util-beans-objects-vectors.ads
|
src/util-beans-objects-vectors.ads
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 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.Vectors;
with Util.Beans.Basic;
package Util.Beans.Objects.Vectors is
package Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Object);
subtype Cursor is Vectors.Cursor;
subtype Vector is Vectors.Vector;
-- Make all the Vectors operations available (a kind of 'use Vectors' for anybody).
function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length;
function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty;
procedure Clear (Container : in out Vector) renames Vectors.Clear;
function First (Container : in Vector) return Cursor renames Vectors.First;
function Last (Container : in Vector) return Cursor renames Vectors.Last;
function Element (Container : in Vector;
Position : in Natural) return Object renames Vectors.Element;
procedure Append (Container : in out Vector;
New_Item : in Object;
Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Element : Object))
renames Vectors.Query_Element;
procedure Update_Element (Container : in out Vector;
Position : in Cursor;
Process : not null access procedure (Element : in out Object))
renames Vectors.Update_Element;
function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element;
function Element (Position : Cursor) return Object renames Vectors.Element;
procedure Next (Position : in out Cursor) renames Vectors.Next;
function Next (Position : Cursor) return Cursor renames Vectors.Next;
function Previous (Position : Cursor) return Cursor renames Vectors.Previous;
procedure Previous (Position : in out Cursor) renames Vectors.Previous;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Bean with private;
type Vector_Bean_Access is access all Vector_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Vector_Bean;
Name : in String) return 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.
procedure Set_Value (From : in out Vector_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
function Create return Object;
private
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Vectors;
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 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.Vectors;
with Util.Beans.Basic;
package Util.Beans.Objects.Vectors is
package Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Object);
subtype Cursor is Vectors.Cursor;
subtype Vector is Vectors.Vector;
-- Make all the Vectors operations available (a kind of 'use Vectors' for anybody).
function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length;
function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty;
procedure Clear (Container : in out Vector) renames Vectors.Clear;
function First (Container : in Vector) return Cursor renames Vectors.First;
function Last (Container : in Vector) return Cursor renames Vectors.Last;
function Element (Container : in Vector;
Position : in Natural) return Object renames Vectors.Element;
procedure Append (Container : in out Vector;
New_Item : in Object;
Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Element : Object))
renames Vectors.Query_Element;
procedure Update_Element (Container : in out Vector;
Position : in Cursor;
Process : not null access procedure (Element : in out Object))
renames Vectors.Update_Element;
function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element;
function Element (Position : Cursor) return Object renames Vectors.Element;
procedure Next (Position : in out Cursor) renames Vectors.Next;
function Next (Position : Cursor) return Cursor renames Vectors.Next;
function Previous (Position : Cursor) return Cursor renames Vectors.Previous;
procedure Previous (Position : in out Cursor) renames Vectors.Previous;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with private;
type Vector_Bean_Access is access all Vector_Bean'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 Vector_Bean;
Name : in String) return Object;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in Vector_Bean) return Natural;
-- Get the element at the given position.
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object;
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
function Create return Object;
private
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with null record;
end Util.Beans.Objects.Vectors;
|
Change the Vector_Bean type to implement the Array_Bean interface
|
Change the Vector_Bean type to implement the Array_Bean interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.