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
|
---|---|---|---|---|---|---|---|---|---|
ac4d3c9fc1c6458f92fcd13c028aec17a1125174
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with AWA.Blogs.Servlets;
with Security.Permissions;
-- == Integration ==
-- To be able to use the `Blogs` module, you will need to add the following line in your
-- GNAT project file:
--
-- with "awa_blogs";
--
-- The `Blog_Module` type manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the `Blog_Module` must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- with AWA.Blogs.Modules;
-- ...
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- 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);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Get the image prefix that was configured for the Blog module.
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
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);
-- 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);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- 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);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet;
end record;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Events;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with AWA.Blogs.Servlets;
with Security.Permissions;
-- == Integration ==
-- To be able to use the `Blogs` module, you will need to add the following line in your
-- GNAT project file:
--
-- with "awa_blogs";
--
-- The `Blog_Module` type manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the `Blog_Module` must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- with AWA.Blogs.Modules;
-- ...
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Definition the events.
package Post_Publish_Event is new AWA.Events.Definition (Name => "blog-post-publish");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- 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);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Get the image prefix that was configured for the Blog module.
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
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);
-- 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);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- 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);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet;
end record;
end AWA.Blogs.Modules;
|
Declare Post_Publish_Event to provide the 'blog-post-publish' event
|
Declare Post_Publish_Event to provide the 'blog-post-publish' event
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
62c56cf9b10192d2936774e348cb5d7307fa70be
|
awa/plugins/awa-votes/src/awa-votes-modules.ads
|
awa/plugins/awa-votes/src/awa-votes-modules.ads
|
-----------------------------------------------------------------------
-- 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 ASF.Applications;
with AWA.Modules;
package AWA.Votes.Modules is
-- The name under which the module is registered.
NAME : constant String := "votes";
-- ------------------------------
-- Module votes
-- ------------------------------
type Vote_Module is new AWA.Modules.Module with private;
type Vote_Module_Access is access all Vote_Module'Class;
-- Initialize the votes module.
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the votes module.
function Get_Vote_Module return Vote_Module_Access;
private
type Vote_Module is new AWA.Modules.Module with null record;
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 ASF.Applications;
with ADO;
with AWA.Modules;
package AWA.Votes.Modules is
-- The name under which the module is registered.
NAME : constant String := "votes";
-- ------------------------------
-- Module votes
-- ------------------------------
type Vote_Module is new AWA.Modules.Module with private;
type Vote_Module_Access is access all Vote_Module'Class;
-- Initialize the votes module.
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the votes module.
function Get_Vote_Module return Vote_Module_Access;
-- Vote for the given element.
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Rating : in Integer);
private
type Vote_Module is new AWA.Modules.Module with null record;
end AWA.Votes.Modules;
|
Move the vote service implementation in the vote module to simplify the implementation
|
Move the vote service implementation in the vote module to simplify the implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
49e725645d4654a59f333011cfff56207d1d1ff4
|
src/asf-components-html-text.adb
|
src/asf-components-html-text.adb
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- 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.Exceptions;
with EL.Objects;
with ASF.Components.Core;
with ASF.Utils;
package body ASF.Components.Html.Text is
use EL.Objects;
TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
-- ------------------------------
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is
begin
return UI.Value;
end Get_Local_Value;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object is
begin
if not EL.Objects.Is_Null (UI.Value) then
return UI.Value;
else
return UI.Get_Attribute (UI.Get_Context.all, "value");
end if;
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object) is
begin
UI.Value := Value;
end Set_Value;
-- ------------------------------
-- Get the converter that is registered on the component.
-- ------------------------------
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access is
begin
return UI.Converter;
end Get_Converter;
-- ------------------------------
-- Set the converter to be used on the component.
-- ------------------------------
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access) is
use type ASF.Converters.Converter_Access;
begin
if Converter = null then
UI.Converter := null;
else
UI.Converter := Converter.all'Unchecked_Access;
end if;
end Set_Converter;
-- ------------------------------
-- Get the value of the component and apply the converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value;
begin
return UIOutput'Class (UI).Get_Formatted_Value (Value, Context);
end Get_Formatted_Value;
-- ------------------------------
-- Format the value by appling the To_String converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String is
use type ASF.Converters.Converter_Access;
begin
if UI.Converter /= null then
return UI.Converter.To_String (Context => Context,
Component => UI,
Value => Value);
else
declare
Converter : constant access ASF.Converters.Converter'Class
:= UI.Get_Converter (Context);
begin
if Converter /= null then
return Converter.To_String (Context => Context,
Component => UI,
Value => Value);
elsif not Is_Null (Value) then
return EL.Objects.To_String (Value);
else
return "";
end if;
end;
end if;
-- If the converter raises an exception, report an error in the logs.
-- At this stage, we know the value and we can report it in this log message.
-- We must queue the exception in the context, so this is done later.
exception
when E : others =>
UI.Log_Error ("Error when converting value '{0}': {1}: {2}",
Util.Beans.Objects.To_String (Value),
Ada.Exceptions.Exception_Name (E),
Ada.Exceptions.Exception_Message (E));
raise;
end Get_Formatted_Value;
procedure Write_Output (UI : in UIOutput;
Context : in out Faces_Context'Class;
Value : in String) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Escape : constant Object := UI.Get_Attribute (Context, "escape");
begin
Writer.Start_Optional_Element ("span");
UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer);
if Is_Null (Escape) or To_Boolean (Escape) then
Writer.Write_Text (Value);
else
Writer.Write_Raw (Value);
end if;
Writer.End_Optional_Element ("span");
end Write_Output;
procedure Encode_Begin (UI : in UIOutput;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UI.Write_Output (Context => Context,
Value => UIOutput'Class (UI).Get_Formatted_Value (Context));
end if;
-- Queue any block converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end Encode_Begin;
-- ------------------------------
-- Label Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.Start_Element ("label");
UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer);
declare
Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for",
Context => Context);
begin
if not Util.Beans.Objects.Is_Null (Value) then
Writer.Write_Attribute ("for", Value);
end if;
Value := UIOutputLabel'Class (UI).Get_Value;
if not Util.Beans.Objects.Is_Null (Value) then
declare
S : constant String
:= UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context);
begin
if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then
Writer.Write_Text (S);
else
Writer.Write_Raw (S);
end if;
end;
end if;
-- Queue and block any converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end;
end if;
end Encode_Begin;
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.End_Element ("label");
end if;
end Encode_End;
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Faces_Context'Class) is
use ASF.Components.Core;
use ASF.Utils;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Params : constant UIParameter_Access_Array := Get_Parameters (UI);
Values : Object_Array (Params'Range);
Result : Ada.Strings.Unbounded.Unbounded_String;
Fmt : constant String := EL.Objects.To_String (UI.Get_Value);
begin
-- Get the values associated with the parameters.
for I in Params'Range loop
Values (I) := Params (I).Get_Value (Context);
end loop;
Formats.Format (Fmt, Values, Result);
UI.Write_Output (Context => Context,
Value => To_String (Result));
end;
end Encode_Begin;
begin
Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES);
Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES);
end ASF.Components.Html.Text;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with EL.Objects;
with ASF.Components.Core;
with ASF.Utils;
package body ASF.Components.Html.Text is
use EL.Objects;
TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
-- ------------------------------
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is
begin
return UI.Value;
end Get_Local_Value;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object is
begin
if not EL.Objects.Is_Null (UI.Value) then
return UI.Value;
else
return UI.Get_Attribute (UI.Get_Context.all, "value");
end if;
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object) is
begin
UI.Value := Value;
end Set_Value;
-- ------------------------------
-- Get the converter that is registered on the component.
-- ------------------------------
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access is
begin
return UI.Converter;
end Get_Converter;
-- ------------------------------
-- Set the converter to be used on the component.
-- ------------------------------
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access) is
use type ASF.Converters.Converter_Access;
begin
if Converter = null then
UI.Converter := null;
else
UI.Converter := Converter.all'Unchecked_Access;
end if;
end Set_Converter;
-- ------------------------------
-- Get the value of the component and apply the converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value;
begin
return UIOutput'Class (UI).Get_Formatted_Value (Value, Context);
end Get_Formatted_Value;
-- ------------------------------
-- Format the value by appling the To_String converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String is
use type ASF.Converters.Converter_Access;
begin
if UI.Converter /= null then
return UI.Converter.To_String (Context => Context,
Component => UI,
Value => Value);
else
declare
Converter : constant access ASF.Converters.Converter'Class
:= UI.Get_Converter (Context);
begin
if Converter /= null then
return Converter.To_String (Context => Context,
Component => UI,
Value => Value);
elsif not Is_Null (Value) then
return EL.Objects.To_String (Value);
else
return "";
end if;
end;
end if;
-- If the converter raises an exception, report an error in the logs.
-- At this stage, we know the value and we can report it in this log message.
-- We must queue the exception in the context, so this is done later.
exception
when E : others =>
UI.Log_Error ("Error when converting value '{0}': {1}: {2}",
Util.Beans.Objects.To_String (Value),
Ada.Exceptions.Exception_Name (E),
Ada.Exceptions.Exception_Message (E));
raise;
end Get_Formatted_Value;
procedure Write_Output (UI : in UIOutput;
Context : in out Faces_Context'Class;
Value : in String) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Escape : constant Object := UI.Get_Attribute (Context, "escape");
begin
Writer.Start_Optional_Element ("span");
UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer);
if Is_Null (Escape) or To_Boolean (Escape) then
Writer.Write_Text (Value);
else
Writer.Write_Raw (Value);
end if;
Writer.End_Optional_Element ("span");
end Write_Output;
procedure Encode_Begin (UI : in UIOutput;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UI.Write_Output (Context => Context,
Value => UIOutput'Class (UI).Get_Formatted_Value (Context));
end if;
-- Queue any block converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end Encode_Begin;
-- ------------------------------
-- Label Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.Start_Element ("label");
UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer);
declare
Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for",
Context => Context);
begin
if not Util.Beans.Objects.Is_Null (Value) then
Writer.Write_Attribute ("for", Value);
end if;
Value := UIOutputLabel'Class (UI).Get_Value;
if not Util.Beans.Objects.Is_Null (Value) then
declare
S : constant String
:= UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context);
begin
if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then
Writer.Write_Text (S);
else
Writer.Write_Raw (S);
end if;
end;
end if;
-- Queue and block any converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end;
end if;
end Encode_Begin;
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.End_Element ("label");
end if;
end Encode_End;
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Faces_Context'Class) is
use ASF.Components.Core;
use ASF.Utils;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Params : constant UIParameter_Access_Array := Get_Parameters (UI);
Values : ASF.Utils.Object_Array (Params'Range);
Result : Ada.Strings.Unbounded.Unbounded_String;
Fmt : constant String := EL.Objects.To_String (UI.Get_Value);
begin
-- Get the values associated with the parameters.
for I in Params'Range loop
Values (I) := Params (I).Get_Value (Context);
end loop;
Formats.Format (Fmt, Values, Result);
UI.Write_Output (Context => Context,
Value => To_String (Result));
end;
end Encode_Begin;
begin
Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES);
Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES);
end ASF.Components.Html.Text;
|
Fix compilation issue on Object_Array type (still ASF.Utils.Object_Array type should be removed some day)
|
Fix compilation issue on Object_Array type
(still ASF.Utils.Object_Array type should be removed some day)
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a2db43b6eac016746da42be1552d90d17de559d4
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_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.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_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.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Call the delete answer
|
Call the delete answer
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8dfb1807a170bbc451e439c16424d31b3275c63f
|
src/ado-sessions.adb
|
src/ado-sessions.adb
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- 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 Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Sequences;
package body ADO.Sessions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class) is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is
begin
if Database.Impl = null then
return ADO.Databases.CLOSED;
end if;
return Database.Impl.Database.Get_Status;
end Get_Status;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
begin
Log.Info ("Closing session");
if Database.Impl /= null then
Database.Impl.Database.Close;
Database.Impl.Counter := Database.Impl.Counter - 1;
if Database.Impl.Counter = 0 then
Free (Database.Impl);
end if;
--
-- if Database.Impl.Proxy /= null then
-- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1;
-- end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Get the database connection.
-- ------------------------------
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is
begin
Check_Session (Database);
return Database.Impl.Database;
end Get_Connection;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Query);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index);
begin
return Database.Impl.Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Log.Info ("Begin transaction");
Check_Session (Database);
Database.Impl.Database.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Log.Info ("Commit transaction");
Check_Session (Database);
Database.Impl.Database.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Log.Info ("Rollback transaction");
Check_Session (Database);
Database.Impl.Database.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Object.Impl.Counter := Object.Impl.Counter + 1;
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
begin
if Object.Impl /= null then
if Object.Impl.Counter = 1 then
Object.Close;
else
Object.Impl.Counter := Object.Impl.Counter - 1;
end if;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- 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 Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Sequences;
package body ADO.Sessions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class) is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is
begin
if Database.Impl = null then
return ADO.Databases.CLOSED;
end if;
return Database.Impl.Database.Get_Status;
end Get_Status;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
begin
Log.Info ("Closing session");
if Database.Impl /= null then
Database.Impl.Database.Close;
Database.Impl.Counter := Database.Impl.Counter - 1;
if Database.Impl.Counter = 0 then
Free (Database.Impl);
end if;
--
-- if Database.Impl.Proxy /= null then
-- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1;
-- end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Get the database connection.
-- ------------------------------
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is
begin
Check_Session (Database);
return Database.Impl.Database;
end Get_Connection;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Query);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index);
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Log.Info ("Begin transaction");
Check_Session (Database);
Database.Impl.Database.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Log.Info ("Commit transaction");
Check_Session (Database);
Database.Impl.Database.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Log.Info ("Rollback transaction");
Check_Session (Database);
Database.Impl.Database.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Object.Impl.Counter := Object.Impl.Counter + 1;
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
begin
if Object.Impl /= null then
if Object.Impl.Counter = 1 then
Object.Close;
else
Object.Impl.Counter := Object.Impl.Counter - 1;
end if;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
Fix parameters for XML queries - Set the query parameters for the XML query
|
Fix parameters for XML queries
- Set the query parameters for the XML query
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
7a26cf66bfdbae3d4c232a17e18630615f67bdcf
|
mat/src/mat-types.ads
|
mat/src/mat-types.ads
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package MAT.Types is
pragma Preelaborate;
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_64;
subtype Target_Size is Interfaces.Unsigned_64;
subtype Target_Offset is Interfaces.Unsigned_64;
type Target_Tick_Ref is new Uint64;
type Target_Thread_Ref is new Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Target_Tick_Ref;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint64;
Length : in Positive := 16) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
-- Convert the string in the form NN.MM into a tick value.
function Tick_Value (Value : in String) return Target_Tick_Ref;
-- Convert the hexadecimal string into an unsigned integer.
function Hex_Value (Value : in String) return Uint64;
end MAT.Types;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- 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 Interfaces;
package MAT.Types is
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_64;
subtype Target_Size is Interfaces.Unsigned_64;
subtype Target_Offset is Interfaces.Unsigned_64;
type Target_Tick_Ref is new Uint64;
type Target_Thread_Ref is new Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Target_Tick_Ref;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint64;
Length : in Positive := 16) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
-- Convert the string in the form NN.MM into a tick value.
function Tick_Value (Value : in String) return Target_Tick_Ref;
-- Convert the hexadecimal string into an unsigned integer.
function Hex_Value (Value : in String) return Uint64;
end MAT.Types;
|
Remove pragma Preelaborate
|
Remove pragma Preelaborate
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
998ddcd769917cf688d6465d834ecd68d2a7d900
|
awa/plugins/awa-settings/regtests/awa-settings-modules-tests.adb
|
awa/plugins/awa-settings/regtests/awa-settings-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-settings-modules-tests -- Unit tests for settings 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.Measures;
with Security.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tests.Helpers.Contexts;
package body AWA.Settings.Modules.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting",
Test_Get_User_Setting'Access);
Caller.Add_Test (Suite, "Test AWA.Settings.Set_User_Setting",
Test_Set_User_Setting'Access);
Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting (perf)",
Test_Perf_User_Setting'Access);
end Add_Tests;
-- ------------------------------
-- Test getting a user setting.
-- ------------------------------
procedure Test_Get_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
for I in 1 .. 10 loop
declare
Name : constant String := "setting-" & Natural'Image (I);
R : constant Integer := AWA.Settings.Get_User_Setting (Name, I);
begin
Util.Tests.Assert_Equals (T, I, R, "Invalid Get_User_Setting result");
end;
end loop;
end Test_Get_User_Setting;
-- ------------------------------
-- Test saving a user setting.
-- ------------------------------
procedure Test_Set_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
for I in 1 .. 10 loop
declare
Name : constant String := "setting-" & Natural'Image (I);
R : Integer;
begin
AWA.Settings.Set_User_Setting (Name, I);
R := AWA.Settings.Get_User_Setting (Name, 0);
Util.Tests.Assert_Equals (T, I, R, "Invalid Set_User_Setting result");
end;
end loop;
end Test_Set_User_Setting;
-- ------------------------------
-- Test performance on user setting.
-- ------------------------------
procedure Test_Perf_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
Ident : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- First pass has to look in the database for the user setting.
-- Second pass finds the setting in the cache.
for Pass in 1 .. 2 loop
declare
Value : Integer;
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
Value := AWA.Settings.Get_User_Setting ("perf-" & Integer'Image (I) & Ident, I);
Util.Tests.Assert_Equals (T, I, Value, "Invalid setting returned");
end loop;
Util.Measures.Report (Stamp, "Getting a user setting (100 times) pass"
& Integer'Image (Pass));
end;
end loop;
declare
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
AWA.Settings.Set_User_Setting ("perf-" & Integer'Image (I) & Ident, I);
end loop;
Util.Measures.Report (Stamp, "Saving and creating user setting (100 times)");
end;
-- Erase the session cache.
Context.Session_Attributes.Clear;
-- Get the user setting that have been created.
declare
Value : Integer;
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
Value := AWA.Settings.Get_User_Setting ("perf-" & Integer'Image (I) & Ident, -1);
Util.Tests.Assert_Equals (T, I, Value, "Invalid setting returned");
end loop;
Util.Measures.Report (Stamp, "Getting a user setting (100 times) load from DB");
end;
end Test_Perf_User_Setting;
end AWA.Settings.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-settings-modules-tests -- Unit tests for settings 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.Measures;
with Security.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tests.Helpers.Contexts;
package body AWA.Settings.Modules.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Settings.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting",
Test_Get_User_Setting'Access);
Caller.Add_Test (Suite, "Test AWA.Settings.Set_User_Setting",
Test_Set_User_Setting'Access);
Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting (perf)",
Test_Perf_User_Setting'Access);
end Add_Tests;
-- ------------------------------
-- Test getting a user setting.
-- ------------------------------
procedure Test_Get_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
for I in 1 .. 10 loop
declare
Name : constant String := "setting-" & Natural'Image (I);
R : constant Integer := AWA.Settings.Get_User_Setting (Name, I);
begin
Util.Tests.Assert_Equals (T, I, R, "Invalid Get_User_Setting result");
end;
end loop;
end Test_Get_User_Setting;
-- ------------------------------
-- Test saving a user setting.
-- ------------------------------
procedure Test_Set_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
for I in 1 .. 10 loop
declare
Name : constant String := "setting-" & Natural'Image (I);
R : Integer;
begin
AWA.Settings.Set_User_Setting (Name, I);
R := AWA.Settings.Get_User_Setting (Name, 0);
Util.Tests.Assert_Equals (T, I, R, "Invalid Set_User_Setting result");
end;
end loop;
end Test_Set_User_Setting;
-- ------------------------------
-- Test performance on user setting.
-- ------------------------------
procedure Test_Perf_User_Setting (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Tests.Helpers.Contexts.Service_Context;
Ident : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- First pass has to look in the database for the user setting.
-- Second pass finds the setting in the cache.
for Pass in 1 .. 2 loop
declare
Value : Integer;
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
Value := AWA.Settings.Get_User_Setting ("perf-" & Integer'Image (I) & Ident, I);
Util.Tests.Assert_Equals (T, I, Value, "Invalid setting returned");
end loop;
Util.Measures.Report (Stamp, "Getting a user setting (100 times) pass"
& Integer'Image (Pass));
end;
end loop;
declare
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
AWA.Settings.Set_User_Setting ("perf-" & Integer'Image (I) & Ident, I);
end loop;
Util.Measures.Report (Stamp, "Saving and creating user setting (100 times)");
end;
-- Erase the session cache.
Context.Session_Attributes.Clear;
-- Get the user setting that have been created.
declare
Value : Integer;
Stamp : Util.Measures.Stamp;
begin
for I in 1 .. 100 loop
Value := AWA.Settings.Get_User_Setting ("perf-" & Integer'Image (I) & Ident, -1);
Util.Tests.Assert_Equals (T, I, Value, "Invalid setting returned");
end loop;
Util.Measures.Report (Stamp, "Getting a user setting (100 times) load from DB");
end;
end Test_Perf_User_Setting;
end AWA.Settings.Modules.Tests;
|
Fix the unit test name
|
Fix the unit test name
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
9493e92cdb86218f4e0adb4d209315c21e1fb04e
|
src/gen-artifacts-yaml.adb
|
src/gen-artifacts-yaml.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-yaml -- Query artifact for Code Generator
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with Ada.Text_IO;
with Util.Strings;
with Text;
with Yaml.Source.File;
with Yaml.Parser;
with Gen.Configs;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Operations;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
with Util.Stacks;
use Yaml;
package body Gen.Artifacts.Yaml is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use Gen.Configs;
use Util.Log;
use type Text.Reference;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Yaml");
type State_Type is (IN_ROOT,
IN_TABLE,
IN_COLUMNS,
IN_KEYS,
IN_COLUMN,
IN_KEY,
IN_UNKOWN);
type Node_Info is record
State : State_Type := IN_UNKOWN;
Name : Text.Reference;
Has_Name : Boolean := False;
Table : Gen.Model.Tables.Table_Definition_Access;
Col : Gen.Model.Tables.Column_Definition_Access;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
procedure Read_Scalar (Node : in Node_Info_Access;
Name : in String;
Value : in String) is
begin
case Node.State is
when IN_TABLE =>
if Node.Table = null then
return;
end if;
Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value);
if Name = "table" then
Node.Table.Table_Name := To_Unbounded_String (Value);
elsif Name = "description" then
Node.Table.Set_Comment (Value);
end if;
when IN_COLUMN | IN_KEY =>
if Node.Col = null then
return;
end if;
Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value);
if Name = "type" then
Node.Col.Set_Type (Value);
elsif Name = "length" then
Node.Col.Sql_Length := Natural'Value (Value);
elsif Name = "column" then
Node.Col.Sql_Name := To_Unbounded_String (Value);
elsif Name = "unique" then
Node.Col.Unique := Value = "true" or Value = "yes";
elsif Name = "nullable" or Name = "optional" then
Node.Col.Not_Null := Value = "false" or Value = "no";
elsif Name = "not-null" or Name = "required" then
Node.Col.Not_Null := Value = "true" or Value = "yes";
elsif Name = "description" then
Node.Col.Set_Comment (Value);
end if;
when others =>
Log.Error ("Scalar {0}: {1} not handled", Name, Value);
end case;
end Read_Scalar;
procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Stack : in out Node_Stack.Stack) is
Node : Node_Info_Access;
New_Node : Node_Info_Access;
begin
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Node.Has_Name := False;
case Node.State is
when IN_ROOT =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Gen.Model.Tables.Create_Table (To_Unbounded_String (Node.Name & ""));
New_Node.State := IN_TABLE;
Model.Register_Table (New_Node.Table);
when IN_TABLE =>
if Node.Name = "fields" or Node.Name = "properties" then
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMNS;
elsif Node.Name = "id" then
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_KEYS;
else
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_TABLE;
end if;
when IN_COLUMNS =>
Node.Table.Add_Column (To_Unbounded_String (Node.Name & ""), Node.Col);
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMN;
when IN_KEYS =>
Node.Table.Add_Column (To_Unbounded_String (Node.Name & ""), Node.Col);
Node.Col.Is_Key := True;
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_KEY;
when others =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.State := IN_UNKOWN;
end case;
else
Node_Stack.Push (Stack);
end if;
end Process_Mapping;
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Model : in out Gen.Model.Packages.Model_Definition;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False) is
Input : Source.Pointer;
P : Parser.Instance;
Cur : Event;
Stack : Node_Stack.Stack;
Node : Node_Info_Access;
Loc : Mark;
begin
Log.Info ("Reading YAML file {0}", File);
Input := Source.File.As_Source (File);
P.Set_Input (Input);
loop
Cur := P.Next;
exit when Cur.Kind = Stream_End;
case Cur.Kind is
when Stream_Start | Document_Start =>
Node_Stack.Push (Stack);
Node := Node_Stack.Current (Stack);
Node.State := IN_ROOT;
when Stream_End | Document_End =>
Node_Stack.Pop (Stack);
when Alias =>
null;
when Scalar =>
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Read_Scalar (Node, Node.Name & "", Cur.Content & "");
Node.Has_Name := False;
else
Node.Name := Cur.Content;
Node.Has_Name := True;
end if;
when Sequence_Start =>
Node_Stack.Push (Stack);
when Sequence_End =>
Node_Stack.Pop (Stack);
when Mapping_Start =>
Process_Mapping (Model, Stack);
when Mapping_End =>
Node_Stack.Pop (Stack);
when Annotation_Start =>
null;
when Annotation_End =>
null;
end case;
end loop;
exception
when E : others =>
Loc := P.Current_Lexer_Token_Start;
Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":"
& Util.Strings.Image (Loc.Column) & ": ",
Ada.Exceptions.Exception_Message (E));
end Read_Model;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
end if;
end Prepare;
end Gen.Artifacts.Yaml;
|
-----------------------------------------------------------------------
-- gen-artifacts-yaml -- Query artifact for Code Generator
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with Util.Strings;
with Text;
with Yaml.Source.File;
with Yaml.Parser;
with Gen.Configs;
with Gen.Model.Tables;
with Gen.Model.Mappings;
with Gen.Model.Operations;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
with Util.Stacks;
use Yaml;
package body Gen.Artifacts.Yaml is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Configs;
use Util.Log;
use type Text.Reference;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Yaml");
type State_Type is (IN_ROOT,
IN_TABLE,
IN_COLUMNS,
IN_KEYS,
IN_COLUMN,
IN_KEY,
IN_UNKOWN);
type Node_Info is record
State : State_Type := IN_UNKOWN;
Name : Text.Reference;
Has_Name : Boolean := False;
Table : Gen.Model.Tables.Table_Definition_Access;
Col : Gen.Model.Tables.Column_Definition_Access;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
procedure Read_Scalar (Node : in Node_Info_Access;
Name : in String;
Value : in String) is
begin
case Node.State is
when IN_TABLE =>
if Node.Table = null then
return;
end if;
Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value);
if Name = "table" then
Node.Table.Table_Name := To_Unbounded_String (Value);
elsif Name = "description" or name = "comment" then
Node.Table.Set_Comment (Value);
end if;
when IN_COLUMN | IN_KEY =>
if Node.Col = null then
return;
end if;
Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value);
if Name = "type" then
Node.Col.Set_Type (Value);
elsif Name = "length" then
Node.Col.Sql_Length := Natural'Value (Value);
elsif Name = "column" then
Node.Col.Sql_Name := To_Unbounded_String (Value);
elsif Name = "unique" then
Node.Col.Unique := Value = "true" or Value = "yes";
elsif Name = "nullable" or Name = "optional" then
Node.Col.Not_Null := Value = "false" or Value = "no";
elsif Name = "not-null" or Name = "required" then
Node.Col.Not_Null := Value = "true" or Value = "yes";
elsif Name = "description" or name = "comment" then
Node.Col.Set_Comment (Value);
end if;
when others =>
Log.Error ("Scalar {0}: {1} not handled", Name, Value);
end case;
end Read_Scalar;
procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Stack : in out Node_Stack.Stack) is
Node : Node_Info_Access;
New_Node : Node_Info_Access;
begin
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Node.Has_Name := False;
case Node.State is
when IN_ROOT =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Gen.Model.Tables.Create_Table (To_Unbounded_String (Node.Name & ""));
New_Node.State := IN_TABLE;
Model.Register_Table (New_Node.Table);
when IN_TABLE =>
if Node.Name = "fields" or Node.Name = "properties" then
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMNS;
elsif Node.Name = "id" then
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_KEYS;
else
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_TABLE;
end if;
when IN_COLUMNS =>
Node.Table.Add_Column (To_Unbounded_String (Node.Name & ""), Node.Col);
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMN;
when IN_KEYS =>
Node.Table.Add_Column (To_Unbounded_String (Node.Name & ""), Node.Col);
Node.Col.Is_Key := True;
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_KEY;
when others =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.State := IN_UNKOWN;
end case;
else
Node_Stack.Push (Stack);
end if;
end Process_Mapping;
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Model : in out Gen.Model.Packages.Model_Definition;
Context : in out Generator'Class) is
Input : Source.Pointer;
P : Parser.Instance;
Cur : Event;
Stack : Node_Stack.Stack;
Node : Node_Info_Access;
Loc : Mark;
begin
Log.Info ("Reading YAML file {0}", File);
Input := Source.File.As_Source (File);
P.Set_Input (Input);
loop
Cur := P.Next;
exit when Cur.Kind = Stream_End;
case Cur.Kind is
when Stream_Start | Document_Start =>
Node_Stack.Push (Stack);
Node := Node_Stack.Current (Stack);
Node.State := IN_ROOT;
when Stream_End | Document_End =>
Node_Stack.Pop (Stack);
when Alias =>
null;
when Scalar =>
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Read_Scalar (Node, Node.Name & "", Cur.Content & "");
Node.Has_Name := False;
else
Node.Name := Cur.Content;
Node.Has_Name := True;
end if;
when Sequence_Start =>
Node_Stack.Push (Stack);
when Sequence_End =>
Node_Stack.Pop (Stack);
when Mapping_Start =>
Process_Mapping (Model, Stack);
when Mapping_End =>
Node_Stack.Pop (Stack);
when Annotation_Start =>
null;
when Annotation_End =>
null;
end case;
end loop;
exception
when E : others =>
Loc := P.Current_Lexer_Token_Start;
Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":"
& Util.Strings.Image (Loc.Column) & ": ",
Ada.Exceptions.Exception_Message (E));
end Read_Model;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
end if;
end Prepare;
end Gen.Artifacts.Yaml;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
a6ae92dc1dab7d465203d5040831e1c688543420
|
src/babel-strategies-default.adb
|
src/babel-strategies-default.adb
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files.Signatures;
with Util.Encoders.SHA1;
with Util.Log.Loggers;
with Babel.Streams.Refs;
package body Babel.Strategies.Default is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Default");
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is
begin
return false; -- not Strategy.Queue.Directories.Is_Empty;
end Has_Directory;
-- Get the next directory that must be processed by the strategy.
overriding
procedure Peek_Directory (Strategy : in out Default_Strategy_Type;
Directory : out Babel.Files.Directory_Type) is
Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element;
begin
-- Strategy.Queue.Directories.Delete_Last;
null;
end Peek_Directory;
-- Set the file queue that the strategy must use.
procedure Set_Queue (Strategy : in out Default_Strategy_Type;
Queue : in Babel.Files.Queues.File_Queue_Access) is
begin
Strategy.Queue := Queue;
end Set_Queue;
overriding
procedure Execute (Strategy : in out Default_Strategy_Type) is
use type Babel.Files.File_Type;
Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer;
File : Babel.Files.File_Type;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Stream : Babel.Streams.Refs.Stream_Ref;
begin
Strategy.Queue.Queue.Dequeue (File, 10.0);
if File = Babel.Files.NO_FILE then
Log.Debug ("Dequeue NO_FILE");
Strategy.Release_Buffer (Content);
else
Log.Debug ("Dequeue {0}", Babel.Files.Get_Path (File));
Strategy.Read_File (File, Stream);
Babel.Files.Signatures.Sha1 (Stream, SHA1);
Babel.Files.Set_Signature (File, SHA1);
if Babel.Files.Is_Modified (File) then
Strategy.Backup_File (File, Stream);
else
Strategy.Release_Buffer (Content);
end if;
end if;
exception
when others =>
Strategy.Release_Buffer (Content);
raise;
end Execute;
-- Scan the directory
overriding
procedure Scan (Strategy : in out Default_Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class) is
procedure Add_Queue (File : in Babel.Files.File_Type) is
begin
Log.Debug ("Queueing {0}", Babel.Files.Get_Path (File));
Strategy.Queue.Add_File (File);
end Add_Queue;
begin
Strategy_Type (Strategy).Scan (Directory, Container);
Container.Each_File (Add_Queue'Access);
end Scan;
-- overriding
-- procedure Add_File (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Element : in Babel.Files.File) is
-- begin
-- Into.Queue.Add_File (Path, Element);
-- end Add_File;
--
-- overriding
-- procedure Add_Directory (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Name : in String) is
-- begin
-- Into.Queue.Add_Directory (Path, Name);
-- end Add_Directory;
end Babel.Strategies.Default;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files.Signatures;
with Util.Encoders.SHA1;
with Util.Log.Loggers;
with Babel.Streams.Refs;
package body Babel.Strategies.Default is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Default");
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is
begin
return false; -- not Strategy.Queue.Directories.Is_Empty;
end Has_Directory;
-- Get the next directory that must be processed by the strategy.
overriding
procedure Peek_Directory (Strategy : in out Default_Strategy_Type;
Directory : out Babel.Files.Directory_Type) is
Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element;
begin
-- Strategy.Queue.Directories.Delete_Last;
null;
end Peek_Directory;
-- Set the file queue that the strategy must use.
procedure Set_Queue (Strategy : in out Default_Strategy_Type;
Queue : in Babel.Files.Queues.File_Queue_Access) is
begin
Strategy.Queue := Queue;
end Set_Queue;
overriding
procedure Execute (Strategy : in out Default_Strategy_Type) is
use type Babel.Files.File_Type;
File : Babel.Files.File_Type;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Stream : Babel.Streams.Refs.Stream_Ref;
begin
Strategy.Queue.Queue.Dequeue (File, 0.1);
if File = Babel.Files.NO_FILE then
Log.Debug ("Dequeue NO_FILE");
else
Log.Debug ("Dequeue {0}", Babel.Files.Get_Path (File));
Strategy.Read_File (File, Stream);
Babel.Files.Signatures.Sha1 (Stream, SHA1);
Babel.Files.Set_Signature (File, SHA1);
if Babel.Files.Is_Modified (File) then
Strategy.Backup_File (File, Stream);
end if;
end if;
end Execute;
-- Scan the directory
overriding
procedure Scan (Strategy : in out Default_Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class) is
procedure Add_Queue (File : in Babel.Files.File_Type) is
begin
Log.Debug ("Queueing {0}", Babel.Files.Get_Path (File));
Strategy.Queue.Add_File (File);
end Add_Queue;
begin
Strategy_Type (Strategy).Scan (Directory, Container);
Container.Each_File (Add_Queue'Access);
end Scan;
-- overriding
-- procedure Add_File (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Element : in Babel.Files.File) is
-- begin
-- Into.Queue.Add_File (Path, Element);
-- end Add_File;
--
-- overriding
-- procedure Add_Directory (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Name : in String) is
-- begin
-- Into.Queue.Add_Directory (Path, Name);
-- end Add_Directory;
end Babel.Strategies.Default;
|
Remove allocation of buffer
|
Remove allocation of buffer
|
Ada
|
apache-2.0
|
stcarrez/babel
|
a853c82440a73f4f0f50c205471bee1b7435d7f3
|
samples/demo_server.adb
|
samples/demo_server.adb
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Upload_Servlet;
with Countries;
with Volume;
with Messages;
with Facebook;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Upload : aliased Upload_Servlet.Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Mapping (Name => "upload", Pattern => "upload.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
-----------------------------------------------------------------------
-- demo_server -- Demo server for Ada Server Faces
-- Copyright (C) 2010, 2011, 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.IO_Exceptions;
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with Servlet.Core.Files;
with Servlet.Core.Measures;
with ASF.Filters.Dump;
with ASF.Beans;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Security.Servlets;
with Util.Beans.Objects;
with Util.Log.Loggers;
with AWS.Net.SSL;
with Countries;
with Volume;
with Messages;
with Facebook;
with Users;
procedure Demo_Server is
CONTEXT_PATH : constant String := "/demo";
CONFIG_PATH : constant String := "samples.properties";
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased Servlet.Core.Files.File_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
Perf : aliased Servlet.Core.Measures.Measure_Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
FB_Auth : aliased Facebook.Facebook_Auth;
Bean : aliased Volume.Compute_Bean;
Conv : aliased Volume.Float_Converter;
None : ASF.Beans.Parameter_Bean_Ref.Ref;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
C.Set ("contextPath", CONTEXT_PATH);
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute",
Util.Beans.Objects.To_Object (Bean'Unchecked_Access,
Util.Beans.Objects.STATIC));
FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id"));
FB_Auth.Set_Application_Secret (C.Get ("facebook.secret"));
FB_Auth.Set_Application_Callback (C.Get ("facebook.callback"));
FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token");
App.Set_Global ("facebook",
Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List));
App.Set_Global ("user",
Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC));
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "volume");
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access);
-- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access);
App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access);
App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access);
App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access);
App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access);
App.Register (Name => "message", Class => "Message_Bean", Params => None);
App.Register (Name => "messages", Class => "Message_List", Params => None);
ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html");
WS.Start;
delay 6000.0;
end Demo_Server;
|
Update the demo server
|
Update the demo server
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2ff3ff440ce78148bc8168a174a9cf07c555c74b
|
testcases/stored_procs/stored_procs.adb
|
testcases/stored_procs/stored_procs.adb
|
with AdaBase;
with Connect;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Stored_Procs is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
stmt_acc : CON.Stmt_Type_access;
procedure dump_result;
procedure dump_result
is
function pad (S : String) return String;
function pad (S : String) return String
is
field : String (1 .. 15) := (others => ' ');
len : Natural := S'Length;
begin
field (1 .. len) := S;
return field;
end pad;
row : ARS.DataRow;
numcols : constant Natural := stmt_acc.column_count;
begin
for c in Natural range 1 .. numcols loop
TIO.Put (pad (stmt_acc.column_name (c)));
end loop;
TIO.Put_Line ("");
for c in Natural range 1 .. numcols loop
TIO.Put ("============== ");
end loop;
TIO.Put_Line ("");
loop
row := stmt_acc.fetch_next;
exit when row.data_exhausted;
for c in Natural range 1 .. numcols loop
TIO.Put (pad (row.column (c).as_string));
end loop;
TIO.Put_Line ("");
end loop;
TIO.Put_Line ("");
end dump_result;
sql : constant String := "CALL multiple_rowsets";
set_fetched : Boolean := True;
set_present : Boolean;
begin
begin
CON.connect_database;
exception
when others =>
TIO.Put_Line ("database connect failed.");
return;
end;
declare
stmt : aliased CON.Stmt_Type := CON.DR.query (sql);
begin
stmt_acc := stmt'Unchecked_Access;
loop
if set_fetched then
dump_result;
end if;
stmt.fetch_next_set (set_present, set_fetched);
exit when not set_present;
end loop;
end;
CON.DR.disconnect;
end Stored_Procs;
|
with AdaBase;
with Connect;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Stored_Procs is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
stmt_acc : CON.Stmt_Type_access;
procedure dump_result;
procedure dump_result
is
function pad (S : String) return String;
function pad (S : String) return String
is
field : String (1 .. 15) := (others => ' ');
len : Natural := S'Length;
begin
field (1 .. len) := S;
return field;
end pad;
row : ARS.DataRow;
numcols : constant Natural := stmt_acc.column_count;
begin
for c in Natural range 1 .. numcols loop
TIO.Put (pad (stmt_acc.column_name (c)));
end loop;
TIO.Put_Line ("");
for c in Natural range 1 .. numcols loop
TIO.Put ("============== ");
end loop;
TIO.Put_Line ("");
loop
row := stmt_acc.fetch_next;
exit when row.data_exhausted;
for c in Natural range 1 .. numcols loop
TIO.Put (pad (row.column (c).as_string));
end loop;
TIO.Put_Line ("");
end loop;
TIO.Put_Line ("");
end dump_result;
sql : constant String := "CALL multiple_rowsets";
set_fetched : Boolean;
set_present : Boolean;
begin
begin
CON.connect_database;
exception
when others =>
TIO.Put_Line ("database connect failed.");
return;
end;
declare
stmt : aliased CON.Stmt_Type := CON.DR.query (sql);
begin
if stmt.successful then
set_fetched := True;
else
TIO.Put_Line ("Stored procedures not supported on " &
CON.DR.trait_driver);
end if;
set_fetched := stmt.successful;
stmt_acc := stmt'Unchecked_Access;
loop
if set_fetched then
dump_result;
end if;
stmt.fetch_next_set (set_present, set_fetched);
exit when not set_present;
end loop;
end;
CON.DR.disconnect;
end Stored_Procs;
|
Make stored procs example fail gracefully
|
Make stored procs example fail gracefully
|
Ada
|
isc
|
jrmarino/AdaBase
|
257b6e880dec668619cc580d345c8a958adfe984
|
demo/text2.adb
|
demo/text2.adb
|
with ada.text_io; use ada.text_io;
-- Simple Lumen demo/test program to illustrate how to display text, using the
-- texture-mapped font facility.
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Float_Text_IO;
with Lumen.Events.Animate;
with Lumen.Window;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
use Lumen;
procedure Text2 is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Nice peppy game-style framerate, in frames per second
Framerate : constant := 60;
-- A font to fall back on
Default_Font_Path : constant String := "fsb.txf";
---------------------------------------------------------------------------
Win : Window.Handle;
Direct : Boolean := True; -- want direct rendering by default
Event : Events.Event_Data;
Wide : Natural := 400;
High : Natural := 400;
Img_Wide : Float;
Img_High : Float;
Rotation : Natural := 0;
Rotating : Boolean := True;
Tx_Font : Font.Txf.Handle;
Object : GL.UInt;
Frame : Natural := 0;
Attrs : Window.Context_Attributes :=
(
(Window.Attr_Red_Size, 8),
(Window.Attr_Green_Size, 8),
(Window.Attr_Blue_Size, 8),
(Window.Attr_Alpha_Size, 8),
(Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Return number blank-padded on the left out to Width; returns full
-- number if it's wider than Width.
function Img (Number : in Integer;
Width : in Positive := 1) return String is
use Ada.Strings.Fixed;
Image : String := Trim (Integer'Image (Number), Side => Ada.Strings.Left);
begin -- Img
if Image'Length >= Width then
return Image;
else
return ((Width - Image'Length) * ' ') & Image;
end if;
end Img;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
Aspect : GL.Double;
begin -- Set_View
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Size of rectangle upon which text is displayed
if Wide > High then
Img_Wide := 1.0;
Img_High := Float (High) / Float (Wide);
else
Img_Wide := Float (Wide) / Float (High);
Img_High := 1.0;
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.MatrixMode (GL.GL_PROJECTION);
GL.LoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GL.Frustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GL.Double (W) / GL.Double (H);
GL.Frustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use type GL.Bitfield;
MW : Natural;
MA : Natural;
MD : Natural;
Scale : Float;
Pad : Float := Img_Wide / 10.0; -- margin width
FNum : String := Img (Frame, 6);
FRate : String (1 .. 6);
begin -- Draw
-- Set a light grey background
GL.ClearColor (0.85, 0.85, 0.85, 0.0);
GL.Clear (GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT);
-- Draw a black rectangle, disabling texturing so we can do plain colors
GL.Disable (GL.GL_TEXTURE_2D);
GL.Disable (GL.GL_BLEND);
GL.Disable (GL.GL_ALPHA_TEST);
GL.Color (Float (0.0), 0.0, 0.0);
GL.glBegin (GL.GL_POLYGON);
begin
GL.Vertex (-Img_Wide, -Img_High, 0.0);
GL.Vertex (-Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, -Img_High, 0.0);
end;
GL.glEnd;
-- Turn texturing back on and set up to draw the text messages
GL.PushMatrix;
GL.Enable (GL.GL_TEXTURE_2D);
GL.Enable (GL.GL_ALPHA_TEST);
GL.AlphaFunc (GL.GL_GEQUAL, 0.0625);
GL.Enable (GL.GL_BLEND);
GL.BlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
GL.Enable (GL.GL_POLYGON_OFFSET_FILL);
GL.PolygonOffset (0.0, -3.0);
GL.Color (Float (0.1), 0.8, 0.1);
-- Draw the frame number, right-justified in upper half of rectangle
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, FNum, MW, MA, MD);
Scale := Img_High / (Float (MA) * 3.0);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FNum);
GL.PopMatrix;
-- Draw the frame number label, left-justified in upper half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "Frame", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "Frame");
GL.PopMatrix;
-- Draw the frame rate, right-justified in lower half of rectangle
GL.PushMatrix;
-- Guard against out-of-range values, and display all question marks if so
begin
Ada.Float_Text_IO.Put (FRate, Events.Animate.FPS (Win), Aft => 3, Exp => 0);
exception
when others =>
FRate := (others => '?');
end;
Font.Txf.Get_String_Metrics (Tx_Font, FRate, MW, MA, MD);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), -Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FRate);
GL.PopMatrix;
-- Draw the frame rate label, left-justified in lower half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "FPS", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), -Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "FPS");
GL.PopMatrix;
GL.PopMatrix;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
GL.MatrixMode (GL.GL_MODELVIEW);
GL.LoadIdentity;
GL.Translate (GL.Double (0.0), 0.0, -4.0);
GL.Rotate (GL.Double (Rotation), 0.0, 1.0, 0.0);
GL.Rotate (GL.Double (Rotation), 0.0, 0.0, 1.0);
-- Now show it
Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for close-window events
procedure Quit_Handler (Event : in Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Event : in Events.Event_Data) is
use type Events.Key_Symbol;
begin -- Key_Handler
if Event.Key_Data.Key = Events.To_Symbol (Ada.Characters.Latin_1.ESC) or
Event.Key_Data.Key = Events.To_Symbol ('q') then
raise Program_Exit;
elsif Event.Key_Data.Key = Events.To_Symbol (Ada.Characters.Latin_1.Space) then
Rotating := not Rotating;
end if;
end Key_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotating then
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
end if;
Frame := Frame + 1;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Text2
-- Load the font we'll be using
if Ada.Command_Line.Argument_Count > 0 then
declare
Font_Path : String := Ada.Command_Line.Argument (1);
begin
Font.Txf.Load (Tx_Font, Font_Path);
exception
when others =>
raise Program_Error with "cannot find font file """ & Font_Path & """";
end;
else
begin
Font.Txf.Load (Tx_Font, Default_Font_Path);
exception
when others =>
begin
Font.Txf.Load (Tx_Font, "demo/" & Default_Font_Path);
exception
when others =>
raise Program_Error with "cannot find default font file """ & Default_Font_Path & """";
end;
end;
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Window.Create (Win,
Name => "Text Demo #2, Revenge of the Text",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Window.Want_Key_Press => True,
Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
Object := Font.Txf.Establish_Texture (Tx_Font, 0, True);
-- Enter the event loop
declare
use Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Key_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Text2;
|
with ada.text_io; use ada.text_io;
-- Simple Lumen demo/test program to illustrate how to display text, using the
-- texture-mapped font facility.
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Float_Text_IO;
with Lumen.Events.Animate;
with Lumen.Events.Keys;
with Lumen.Window;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
use Lumen;
procedure Text2 is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 360.0;
-- Nice peppy game-style framerate, in frames per second
Framerate : constant := 60;
-- A font to fall back on
Default_Font_Path : constant String := "fsb.txf";
-- Keystrokes we care about
Escape : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC));
Space : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.Space));
Letter_q : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LC_Q));
---------------------------------------------------------------------------
Win : Window.Handle;
Direct : Boolean := True; -- want direct rendering by default
Event : Events.Event_Data;
Wide : Natural := 400;
High : Natural := 400;
Img_Wide : Float;
Img_High : Float;
Rotation : Float := 0.0;
Increment : Float := 1.0;
Rotating : Boolean := True;
Tx_Font : Font.Txf.Handle;
Object : GL.UInt;
Frame : Natural := 0;
Attrs : Window.Context_Attributes :=
(
(Window.Attr_Red_Size, 8),
(Window.Attr_Green_Size, 8),
(Window.Attr_Blue_Size, 8),
(Window.Attr_Alpha_Size, 8),
(Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Return number blank-padded on the left out to Width; returns full
-- number if it's wider than Width.
function Img (Number : in Integer;
Width : in Positive := 1) return String is
use Ada.Strings.Fixed;
Image : String := Trim (Integer'Image (Number), Side => Ada.Strings.Left);
begin -- Img
if Image'Length >= Width then
return Image;
else
return ((Width - Image'Length) * ' ') & Image;
end if;
end Img;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
Aspect : GL.Double;
begin -- Set_View
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Size of rectangle upon which text is displayed
if Wide > High then
Img_Wide := 1.0;
Img_High := Float (High) / Float (Wide);
else
Img_Wide := Float (Wide) / Float (High);
Img_High := 1.0;
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.MatrixMode (GL.GL_PROJECTION);
GL.LoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GL.Frustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GL.Double (W) / GL.Double (H);
GL.Frustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use type GL.Bitfield;
MW : Natural;
MA : Natural;
MD : Natural;
Scale : Float;
Pad : Float := Img_Wide / 10.0; -- margin width
FNum : String := Img (Frame, 6);
FRate : String (1 .. 6);
begin -- Draw
-- Set a light grey background
GL.ClearColor (0.85, 0.85, 0.85, 0.0);
GL.Clear (GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT);
-- Draw a black rectangle, disabling texturing so we can do plain colors
GL.Disable (GL.GL_TEXTURE_2D);
GL.Disable (GL.GL_BLEND);
GL.Disable (GL.GL_ALPHA_TEST);
GL.Color (Float (0.0), 0.0, 0.0);
GL.glBegin (GL.GL_POLYGON);
begin
GL.Vertex (-Img_Wide, -Img_High, 0.0);
GL.Vertex (-Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, -Img_High, 0.0);
end;
GL.glEnd;
-- Turn texturing back on and set up to draw the text messages
GL.PushMatrix;
GL.Enable (GL.GL_TEXTURE_2D);
GL.Enable (GL.GL_ALPHA_TEST);
GL.AlphaFunc (GL.GL_GEQUAL, 0.0625);
GL.Enable (GL.GL_BLEND);
GL.BlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
GL.Enable (GL.GL_POLYGON_OFFSET_FILL);
GL.PolygonOffset (0.0, -3.0);
GL.Color (Float (0.1), 0.8, 0.1);
-- Draw the frame number, right-justified in upper half of rectangle
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, FNum, MW, MA, MD);
Scale := Img_High / (Float (MA) * 3.0);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FNum);
GL.PopMatrix;
-- Draw the frame number label, left-justified in upper half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "Frame", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "Frame");
GL.PopMatrix;
-- Draw the frame rate, right-justified in lower half of rectangle
GL.PushMatrix;
-- Guard against out-of-range values, and display all question marks if so
begin
Ada.Float_Text_IO.Put (FRate, Events.Animate.FPS (Win), Aft => 3, Exp => 0);
exception
when others =>
FRate := (others => '?');
end;
Font.Txf.Get_String_Metrics (Tx_Font, FRate, MW, MA, MD);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), -Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FRate);
GL.PopMatrix;
-- Draw the frame rate label, left-justified in lower half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "FPS", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), -Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "FPS");
GL.PopMatrix;
GL.PopMatrix;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
GL.MatrixMode (GL.GL_MODELVIEW);
GL.LoadIdentity;
GL.Translate (GL.Double (0.0), 0.0, -4.0);
GL.Rotate (GL.Double (Rotation), 0.0, 1.0, 0.0);
GL.Rotate (GL.Double (Rotation), 0.0, 0.0, 1.0);
-- Now show it
Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for close-window events
procedure Quit_Handler (Event : in Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Event : in Events.Event_Data) is
use type Events.Key_Symbol;
begin -- Key_Handler
case Event.Key_Data.Key is
when Escape | Letter_q =>
raise Program_Exit;
when Space =>
Rotating := not Rotating;
when Events.Keys.Up =>
if Increment * 2.0 < Float'Last then
Increment := Increment * 2.0;
end if;
when Events.Keys.Down =>
if Increment / 2.0 > 0.0 then
Increment := Increment / 2.0;
end if;
when others =>
null;
end case;
end Key_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotating then
if Rotation >= Max_Rotation then
Rotation := 0.0;
else
Rotation := Rotation + Increment;
end if;
end if;
Frame := Frame + 1;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Text2
-- Load the font we'll be using
if Ada.Command_Line.Argument_Count > 0 then
declare
Font_Path : String := Ada.Command_Line.Argument (1);
begin
Font.Txf.Load (Tx_Font, Font_Path);
exception
when others =>
raise Program_Error with "cannot find font file """ & Font_Path & """";
end;
else
begin
Font.Txf.Load (Tx_Font, Default_Font_Path);
exception
when others =>
begin
Font.Txf.Load (Tx_Font, "demo/" & Default_Font_Path);
exception
when others =>
raise Program_Error with "cannot find default font file """ & Default_Font_Path & """";
end;
end;
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Create Lumen window, accepting most defaults
Window.Create (Win,
Name => "Text Demo #2, Revenge of the Text",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Window.Want_Key_Press => True,
Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
Object := Font.Txf.Establish_Texture (Tx_Font, 0, True);
-- Enter the event loop
declare
use Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Key_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Text2;
|
Add a bunch of fancy shit to the latest text demo
|
Add a bunch of fancy shit to the latest text demo
|
Ada
|
isc
|
darkestkhan/lumen2,darkestkhan/lumen
|
1aaad9f576179e495cd648a52ca40c630aa041bf
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- 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 Util.Test_Caller;
with Util.Strings;
with ADO;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete",
Test_Delete_Member'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept",
Test_Accept_Invitation'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Member_List",
Test_List_Members'Access);
end Add_Tests;
-- ------------------------------
-- Verify the anonymous access for the invitation page.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply,
"This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply,
"This invitation is invalid (key)");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired",
Reply, "This invitation is invalid (key)");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "Accept invitation", Reply,
"Accept invitation page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
Check : AWA.Workspaces.Beans.Invitation_Bean;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
T.Assert (Invite.Get_Member.Is_Inserted, "The invitation has a workspace member");
Check.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key);
T.Member_ID := Invite.Get_Member.Get_Id;
end Test_Invite_User;
-- ------------------------------
-- Test deleting the member.
-- ------------------------------
procedure Test_Delete_Member (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
declare
Id : constant String := ADO.Identifier'Image (T.Member_Id);
begin
Request.Set_Parameter ("member-id", Id);
Request.Set_Parameter ("delete", "1");
Request.Set_Parameter ("delete-member-form", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html",
"delete-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after delete member operation");
ASF.Tests.Assert_Contains (T, "deleteDialog_" & Id (Id'First + 1 .. Id'Last), Reply,
"Delete member dialog operation response is invalid");
end;
end Test_Delete_Member;
-- ------------------------------
-- Test accepting the invitation.
-- ------------------------------
procedure Test_Accept_Invitation (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Recover_Password ("[email protected]");
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/accept-invitation.html?key="
& To_String (T.Key),
"accept-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/main.html", Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation;
-- ------------------------------
-- Test listing the members of the workspace.
-- ------------------------------
procedure Test_List_Members (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/members.html",
"member-list.html");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invited user is listed in the members page");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invite user (owner) is listed in the members page");
end Test_List_Members;
end AWA.Workspaces.Tests;
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- 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 ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Tests.Helpers.Users;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete",
Test_Delete_Member'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept",
Test_Accept_Invitation'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Member_List",
Test_List_Members'Access);
end Add_Tests;
-- ------------------------------
-- Verify the anonymous access for the invitation page.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply,
"This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply,
"This invitation is invalid (key)");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired",
Reply, "This invitation is invalid (key)");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "Accept invitation", Reply,
"Accept invitation page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
T.Assert (Invite.Get_Member.Is_Inserted, "The invitation has a workspace member");
T.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key);
T.Member_ID := Invite.Get_Member.Get_Id;
end Test_Invite_User;
-- ------------------------------
-- Test deleting the member.
-- ------------------------------
procedure Test_Delete_Member (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
declare
Id : constant String := ADO.Identifier'Image (T.Member_Id);
begin
Request.Set_Parameter ("member-id", Id);
Request.Set_Parameter ("delete", "1");
Request.Set_Parameter ("delete-member-form", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html",
"delete-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after delete member operation");
ASF.Tests.Assert_Contains (T, "deleteDialog_" & Id (Id'First + 1 .. Id'Last), Reply,
"Delete member dialog operation response is invalid");
end;
end Test_Delete_Member;
-- ------------------------------
-- Test accepting the invitation.
-- ------------------------------
procedure Test_Accept_Invitation (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Recover_Password ("[email protected]");
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/accept-invitation.html?key="
& To_String (T.Key),
"accept-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/main.html", Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation;
-- ------------------------------
-- Test listing the members of the workspace.
-- ------------------------------
procedure Test_List_Members (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/members.html",
"member-list.html");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invited user is listed in the members page");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invite user (owner) is listed in the members page");
end Test_List_Members;
end AWA.Workspaces.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
08b8b594e9412400545d83b397780a34938d335d
|
src/util-serialize-io-json.adb
|
src/util-serialize-io-json.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Streams;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
procedure Error (Handler : in out Parser;
Message : in String) is
begin
raise Parse_Error with Natural'Image (Handler.Line_Number) & ":" & Message;
end Error;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a number
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
loop
Parse_Value (P, "");
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
null;
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
P.Error ("Missing '""' to terminate the string");
return;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
-- ------------------------------
-- Parse a number
-- ------------------------------
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer) is
Value : Long_Long_Integer := 0;
Num : Long_Long_Integer;
C : Character;
begin
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Num := Character'Pos (C) - Character'Pos ('0');
Value := Value * 10 + Num;
end loop;
Result := Value;
end Parse_Number;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Streams;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
procedure Error (Handler : in out Parser;
Message : in String) is
begin
raise Parse_Error with Natural'Image (Handler.Line_Number) & ":" & Message;
end Error;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a number
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
Peek (P, Token);
if Token /= T_RIGHT_BRACKET then
Put_Back (P, Token);
loop
Parse_Value (P, "");
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
null;
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
P.Error ("Missing '""' to terminate the string");
return;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
-- ------------------------------
-- Parse a number
-- ------------------------------
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer) is
Value : Long_Long_Integer := 0;
Num : Long_Long_Integer;
C : Character;
begin
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Num := Character'Pos (C) - Character'Pos ('0');
Value := Value * 10 + Num;
end loop;
Result := Value;
end Parse_Number;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
Fix parsing of empty JSON arrays
|
Fix parsing of empty JSON arrays
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2f22114d792470f1285d736bd1e6496d4dfecf5b
|
awa/regtests/awa_command.adb
|
awa/regtests/awa_command.adb
|
-----------------------------------------------------------------------
-- awa_command - Tests for AWA command
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands;
with Util.Tests;
with AWA.Tests;
with AWA.Commands.Drivers;
with AWA.Commands.List;
with AWA.Commands.Start;
with AWA.Commands.Stop;
with AWA.Commands.Info;
with Servlet.Server;
with ADO.Drivers;
with AWA.Testsuite;
procedure AWA_Command is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "awa",
Container_Type => Servlet.Server.Container);
package List_Command is
new AWA.Commands.List (Server_Commands);
package Start_Command is
new AWA.Commands.Start (Server_Commands);
package Stop_Command is
new AWA.Commands.Stop (Server_Commands);
package Info_Command is
new AWA.Commands.Info (Server_Commands);
App : aliased AWA.Tests.Test_Application;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite;
pragma Unreferenced (Suite);
begin
ADO.Drivers.Initialize;
Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
AWA.Commands.Print (Context, E);
end AWA_Command;
|
-----------------------------------------------------------------------
-- awa_command - Tests for AWA command
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands;
with Util.Tests;
with AWA.Commands.Drivers;
with AWA.Commands.List;
with AWA.Commands.Start;
with AWA.Commands.Stop;
with AWA.Commands.Info;
with Servlet.Server;
with ADO.Drivers;
with AWA.Testsuite;
with AWA_Test_App;
procedure AWA_Command is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "awa",
Container_Type => Servlet.Server.Container);
package List_Command is
new AWA.Commands.List (Server_Commands);
package Start_Command is
new AWA.Commands.Start (Server_Commands);
package Stop_Command is
new AWA.Commands.Stop (Server_Commands);
package Info_Command is
new AWA.Commands.Info (Server_Commands);
App : aliased AWA_Test_App.Application;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite;
pragma Unreferenced (Suite);
begin
ADO.Drivers.Initialize;
Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
AWA.Commands.Print (Context, E);
end AWA_Command;
|
Update the awa_command to use the test application
|
Update the awa_command to use the test application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
da39ff8dcfdd829ec8ca59bf20d8c355057aa1ba
|
awa/plugins/awa-storages/src/awa-storages-modules.ads
|
awa/plugins/awa-storages/src/awa-storages-modules.ads
|
-----------------------------------------------------------------------
-- awa-storages-modules -- Storage management module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with AWA.Modules;
with AWA.Storages.Services;
package AWA.Storages.Modules is
NAME : constant String := "storages";
type Storage_Module is new AWA.Modules.Module with private;
type Storage_Module_Access is access all Storage_Module'Class;
-- Initialize the storage module.
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the storage manager.
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Create a storage manager. This operation can be overriden to provide another
-- storage service implementation.
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Get the storage module instance associated with the current application.
function Get_Storage_Module return Storage_Module_Access;
-- Get the storage manager instance associated with the current application.
function Get_Storage_Manager return Services.Storage_Service_Access;
private
type Storage_Module is new AWA.Modules.Module with record
Manager : Services.Storage_Service_Access := null;
end record;
end AWA.Storages.Modules;
|
-----------------------------------------------------------------------
-- awa-storages-modules -- Storage management module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with AWA.Modules;
with AWA.Storages.Services;
package AWA.Storages.Modules is
NAME : constant String := "storages";
type Storage_Module is new AWA.Modules.Module with private;
type Storage_Module_Access is access all Storage_Module'Class;
-- Initialize the storage module.
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the storage manager.
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Create a storage manager. This operation can be overridden to provide another
-- storage service implementation.
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Get the storage module instance associated with the current application.
function Get_Storage_Module return Storage_Module_Access;
-- Get the storage manager instance associated with the current application.
function Get_Storage_Manager return Services.Storage_Service_Access;
private
type Storage_Module is new AWA.Modules.Module with record
Manager : Services.Storage_Service_Access := null;
end record;
end AWA.Storages.Modules;
|
Fix comments
|
Fix comments
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
932ecc21186661dd183e8f1f333512bd0fa5f899
|
awa/plugins/awa-mail/src/awa-mail-components-messages.ads
|
awa/plugins/awa-mail/src/awa-mail-components-messages.ads
|
-----------------------------------------------------------------------
-- awa-mail-components-recipients -- Mail UI Recipients
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
-- === Mail Messages ===
-- The <b>AWA.Mail.Components.Messages</b> package defines the UI components
-- to represent the email message with its recipients, subject and body.
--
-- The mail message is retrieved by looking at the parent UI component until a
-- <tt>UIMailMessage</tt> component is found. The mail message recipients are initialized
-- during the render response JSF phase, that is when <tt>Encode_End</tt> are called.
package AWA.Mail.Components.Messages is
-- ------------------------------
-- The mail recipient
-- ------------------------------
type UIMailMessage is new UIMailComponent with private;
type UIMailMessage_Access is access all UIMailMessage'Class;
-- Set the mail message instance.
procedure Set_Message (UI : in out UIMailMessage;
Message : in AWA.Mail.Clients.Mail_Message_Access);
-- Get the mail message instance.
overriding
function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access;
-- Send the mail.
overriding
procedure Encode_End (UI : in UIMailMessage;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Finalize and release the mail message.
overriding
procedure Finalize (UI : in out UIMailMessage);
-- ------------------------------
-- The mail subject
-- ------------------------------
type UIMailSubject is new UIMailComponent with private;
-- Render the mail subject and initializes the message with its content.
overriding
procedure Encode_Children (UI : in UIMailSubject;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- The mail body
-- ------------------------------
type UIMailBody is new UIMailComponent with private;
-- Render the mail body and initializes the message with its content.
overriding
procedure Encode_Children (UI : in UIMailBody;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
private
type UIMailMessage is new UIMailComponent with record
Message : AWA.Mail.Clients.Mail_Message_Access;
end record;
type UIMailBody is new UIMailComponent with null record;
type UIMailSubject is new UIMailComponent with null record;
end AWA.Mail.Components.Messages;
|
-----------------------------------------------------------------------
-- awa-mail-components-recipients -- Mail UI Recipients
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
-- === Mail Messages ===
-- The `AWA.Mail.Components.Messages` package defines the UI components
-- to represent the email message with its recipients, subject and body.
--
-- The mail message is retrieved by looking at the parent UI component until a
-- `UIMailMessage` component is found. The mail message recipients are initialized
-- during the render response JSF phase, that is when `Encode_End` are called.
--
-- The `<mail:body>` component holds the message body. This component can
-- include a facelet labeled `alternative` in which case it will be used
-- to build the `text/plain` mail message. The default content type for
-- `<mail:body>` is `text/html` but this can be changed by using the
-- `type` attribute.
--
-- <mail:body type='text/html'>
-- <facet name='alternative'>
-- The text/plain mail message.
-- </facet>
-- The text/html mail message.
-- </mail:body>
package AWA.Mail.Components.Messages is
ALTERNATIVE_NAME : constant String := "alternative";
-- ------------------------------
-- The mail recipient
-- ------------------------------
type UIMailMessage is new UIMailComponent with private;
type UIMailMessage_Access is access all UIMailMessage'Class;
-- Set the mail message instance.
procedure Set_Message (UI : in out UIMailMessage;
Message : in AWA.Mail.Clients.Mail_Message_Access);
-- Get the mail message instance.
overriding
function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access;
-- Send the mail.
overriding
procedure Encode_End (UI : in UIMailMessage;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Finalize and release the mail message.
overriding
procedure Finalize (UI : in out UIMailMessage);
-- ------------------------------
-- The mail subject
-- ------------------------------
type UIMailSubject is new UIMailComponent with private;
-- Render the mail subject and initializes the message with its content.
overriding
procedure Encode_Children (UI : in UIMailSubject;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- The mail body
-- ------------------------------
type UIMailBody is new UIMailComponent with private;
-- Render the mail body and initializes the message with its content.
overriding
procedure Encode_Children (UI : in UIMailBody;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
private
type UIMailMessage is new UIMailComponent with record
Message : AWA.Mail.Clients.Mail_Message_Access;
end record;
type UIMailBody is new UIMailComponent with null record;
type UIMailSubject is new UIMailComponent with null record;
end AWA.Mail.Components.Messages;
|
Declare ALTERNATIVE_NAME and update documentation
|
Declare ALTERNATIVE_NAME and update documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e05e74c06fee645ac781ce4e55b51b535fd8f8b6
|
src/security-auth-oauth.ads
|
src/security-auth-oauth.ads
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.OAuth.Clients;
private package Security.Auth.OAuth is
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
type Manager is abstract new Security.Auth.Manager with private;
-- Initialize the authentication realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the OAuth access token and retrieve information about the user.
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication) is abstract;
private
type Manager is abstract new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
Scope : Unbounded_String;
App : Security.OAuth.Clients.Application;
end record;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.OAuth.Clients;
private package Security.Auth.OAuth is
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
type Manager is abstract new Security.Auth.Manager with private;
-- Initialize the authentication realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the OAuth access token and retrieve information about the user.
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication) is abstract;
private
type Manager is abstract new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
Scope : Unbounded_String;
App : Security.OAuth.Clients.Application;
end record;
end Security.Auth.OAuth;
|
Add some comment
|
Add some comment
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
ae3c1cff609dd644543621ba470b82b613ff86e6
|
src/ado-databases.adb
|
src/ado-databases.adb
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Connections
-- 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 Util.Log;
with Util.Log.Loggers;
with ADO.SQL;
with Ada.Unchecked_Deallocation;
with System.Address_Image;
package body ADO.Databases is
use Util.Log;
use ADO.Drivers;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases");
-- ------------------------------
-- Get the database connection status.
-- ------------------------------
function Get_Status (Database : in Connection) return Connection_Status is
begin
if Database.Impl = null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
declare
Query : Query_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return ADO.Statements.Create_Statement (Query);
end;
end Create_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Connection;
Query : in String)
return Query_Statement is
begin
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
declare
Stmt : Query_Statement_Access := Database.Impl.all.Create_Statement (null);
begin
Append (Query => Stmt.all, SQL => Query);
return ADO.Statements.Create_Statement (Stmt);
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
if Database.Impl = null then
Log.Error ("Database connection is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Load_Schema (Schema);
end Load_Schema;
-- ------------------------------
-- Close the database connection
-- ------------------------------
procedure Close (Database : in out Connection) is
begin
Log.Info ("Closing database connection");
if Database.Impl /= null then
Database.Impl.Close;
end if;
end Close;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Connection) is
begin
Log.Info ("Begin transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Connection) is
begin
Log.Info ("Commit transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Connection) is
begin
Log.Info ("Rollback transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "Database implementation is not initialized";
end if;
Database.Impl.Rollback;
end Rollback;
procedure Execute (Database : in Master_Connection;
SQL : in Query_String) is
begin
Log.Info ("Execute: {0}", SQL);
Database.Impl.Execute (SQL);
end Execute;
procedure Execute (Database : in Master_Connection;
SQL : in Query_String;
Id : out Identifier) is
begin
Log.Info ("Execute: {0}", SQL);
Database.Impl.Execute (SQL, Id);
end Execute;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Log.Info ("Create delete statement");
declare
Stmt : Delete_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return Create_Statement (Stmt);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Log.Info ("Create insert statement");
declare
Stmt : constant Insert_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return Create_Statement (Stmt.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Log.Info ("Create insert statement");
return Create_Statement (Database.Impl.all.Create_Statement (Table));
end Create_Statement;
-- ------------------------------
-- Adjust the connection reference counter
-- ------------------------------
overriding
procedure Adjust (Object : in out Connection) is
begin
if Object.Impl /= null then
Log.Debug ("Adjust {0} : {1}", System.Address_Image (Object.Impl.all'Address),
Natural'Image (Object.Impl.Count));
Object.Impl.Count := Object.Impl.Count + 1;
end if;
end Adjust;
-- ------------------------------
-- Releases the connection reference counter
-- ------------------------------
overriding
procedure Finalize (Object : in out Connection) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Database_Connection'Class,
Name => Database_Connection_Access);
begin
if Object.Impl /= null then
Log.Debug ("Finalize {0} : {1}", System.Address_Image (Object.Impl.all'Address),
Natural'Image (Object.Impl.Count));
Object.Impl.Count := Object.Impl.Count - 1;
if Object.Impl.Count = 0 then
Free (Object.Impl);
end if;
end if;
end Finalize;
-- ------------------------------
-- Attempts to establish a connection with the data source
-- that this DataSource object represents.
-- ------------------------------
function Get_Connection (Controller : in DataSource)
return Master_Connection'Class is
Connection : ADO.Drivers.Database_Connection_Access;
begin
Log.Info ("Get master connection from data-source");
Controller.Create_Connection (Connection);
return Master_Connection '(Ada.Finalization.Controlled with
Impl => Connection);
end Get_Connection;
-- ------------------------------
-- Set the master data source
-- ------------------------------
procedure Set_Master (Controller : in out Replicated_DataSource;
Master : in DataSource_Access) is
begin
Controller.Master := Master;
end Set_Master;
-- ------------------------------
-- Get the master data source
-- ------------------------------
function Get_Master (Controller : in Replicated_DataSource)
return DataSource_Access is
begin
return Controller.Master;
end Get_Master;
-- ------------------------------
-- Set the slave data source
-- ------------------------------
procedure Set_Slave (Controller : in out Replicated_DataSource;
Slave : in DataSource_Access) is
begin
Controller.Slave := Slave;
end Set_Slave;
-- ------------------------------
-- Get the slave data source
-- ------------------------------
function Get_Slave (Controller : in Replicated_DataSource)
return DataSource_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.Databases;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Connections
-- 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 Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with System.Address_Image;
with ADO.Statements.Create;
package body ADO.Databases is
use Util.Log;
use ADO.Drivers;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases");
-- ------------------------------
-- Get the database connection status.
-- ------------------------------
function Get_Status (Database : in Connection) return Connection_Status is
begin
if Database.Impl = null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
declare
Query : constant Query_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Query);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Connection;
Query : in String)
return Query_Statement is
begin
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
declare
Stmt : constant Query_Statement_Access := Database.Impl.all.Create_Statement (null);
begin
Append (Query => Stmt.all, SQL => Query);
return ADO.Statements.Create.Create_Statement (Stmt);
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
if Database.Impl = null then
Log.Error ("Database connection is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Load_Schema (Schema);
end Load_Schema;
-- ------------------------------
-- Close the database connection
-- ------------------------------
procedure Close (Database : in out Connection) is
begin
Log.Info ("Closing database connection");
if Database.Impl /= null then
Database.Impl.Close;
end if;
end Close;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Connection) is
begin
Log.Info ("Begin transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Connection) is
begin
Log.Info ("Commit transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "No connection to the database";
end if;
Database.Impl.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Connection) is
begin
Log.Info ("Rollback transaction");
if Database.Impl = null then
Log.Error ("Database implementation is not initialized");
raise NOT_OPEN with "Database implementation is not initialized";
end if;
Database.Impl.Rollback;
end Rollback;
procedure Execute (Database : in Master_Connection;
SQL : in Query_String) is
begin
Log.Info ("Execute: {0}", SQL);
Database.Impl.Execute (SQL);
end Execute;
procedure Execute (Database : in Master_Connection;
SQL : in Query_String;
Id : out Identifier) is
begin
Log.Info ("Execute: {0}", SQL);
Database.Impl.Execute (SQL, Id);
end Execute;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Log.Info ("Create delete statement");
declare
Stmt : constant Delete_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Log.Info ("Create insert statement");
declare
Stmt : constant Insert_Statement_Access := Database.Impl.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
function Create_Statement (Database : in Master_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Log.Info ("Create update statement");
return ADO.Statements.Create.Create_Statement (Database.Impl.all.Create_Statement (Table));
end Create_Statement;
-- ------------------------------
-- Adjust the connection reference counter
-- ------------------------------
overriding
procedure Adjust (Object : in out Connection) is
begin
if Object.Impl /= null then
Log.Debug ("Adjust {0} : {1}", System.Address_Image (Object.Impl.all'Address),
Natural'Image (Object.Impl.Count));
Object.Impl.Count := Object.Impl.Count + 1;
end if;
end Adjust;
-- ------------------------------
-- Releases the connection reference counter
-- ------------------------------
overriding
procedure Finalize (Object : in out Connection) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Database_Connection'Class,
Name => Database_Connection_Access);
begin
if Object.Impl /= null then
Log.Debug ("Finalize {0} : {1}", System.Address_Image (Object.Impl.all'Address),
Natural'Image (Object.Impl.Count));
Object.Impl.Count := Object.Impl.Count - 1;
if Object.Impl.Count = 0 then
Free (Object.Impl);
end if;
end if;
end Finalize;
-- ------------------------------
-- Attempts to establish a connection with the data source
-- that this DataSource object represents.
-- ------------------------------
function Get_Connection (Controller : in DataSource)
return Master_Connection'Class is
Connection : ADO.Drivers.Database_Connection_Access;
begin
Log.Info ("Get master connection from data-source");
Controller.Create_Connection (Connection);
return Master_Connection '(Ada.Finalization.Controlled with
Impl => Connection);
end Get_Connection;
-- ------------------------------
-- Set the master data source
-- ------------------------------
procedure Set_Master (Controller : in out Replicated_DataSource;
Master : in DataSource_Access) is
begin
Controller.Master := Master;
end Set_Master;
-- ------------------------------
-- Get the master data source
-- ------------------------------
function Get_Master (Controller : in Replicated_DataSource)
return DataSource_Access is
begin
return Controller.Master;
end Get_Master;
-- ------------------------------
-- Set the slave data source
-- ------------------------------
procedure Set_Slave (Controller : in out Replicated_DataSource;
Slave : in DataSource_Access) is
begin
Controller.Slave := Slave;
end Set_Slave;
-- ------------------------------
-- Get the slave data source
-- ------------------------------
function Get_Slave (Controller : in Replicated_DataSource)
return DataSource_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.Databases;
|
Use the Create_Statement functions now defined in ADO.Statements.Create package
|
Use the Create_Statement functions now defined in ADO.Statements.Create package
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
cc73e2317493a8beb383be8b3140b6b657049abb
|
regtests/util-streams-sockets-tests.adb
|
regtests/util-streams-sockets-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String) is
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class) is
pragma Unreferenced (Stream);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1327db4981825c391e5e4759f419bd189a41585c
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Events;
package AWA.Workspaces.Modules is
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
end record;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Users.Models;
with AWA.Events;
package AWA.Workspaces.Modules is
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
end record;
end AWA.Workspaces.Modules;
|
Add the Inviter parameter to the Load_Invitation procedure
|
Add the Inviter parameter to the Load_Invitation procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2cfb27849923fc744430b10c535e180be52d4f24
|
samples/xmlrd.adb
|
samples/xmlrd.adb
|
-----------------------------------------------------------------------
-- xrds -- XRDS parser example
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Beans;
with Util.Beans.Objects;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Serialize.IO.XML;
procedure Xmlrd is
use Ada.Containers;
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
Reader : Util.Serialize.IO.XML.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
type Service_Fields is (FIELD_PRIORITY, FIELD_TYPE, FIELD_URI, FIELD_LOCAL_ID, FIELD_DELEGATE);
type Service is record
Priority : Integer;
URI : Ada.Strings.Unbounded.Unbounded_String;
RDS_Type : Ada.Strings.Unbounded.Unbounded_String;
Delegate : Ada.Strings.Unbounded.Unbounded_String;
Local_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Service_Access is access all Service;
package Service_Vector is
new Ada.Containers.Vectors (Element_Type => Service,
Index_Type => Natural);
procedure Print (P : in Service_Vector.Cursor);
procedure Print (P : in Service);
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object);
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object;
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object) is
begin
Ada.Text_IO.Put_Line ("Set member " & Service_Fields'Image (Field)
& " to " & Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_PRIORITY =>
P.Priority := Util.Beans.Objects.To_Integer (Value);
when FIELD_TYPE =>
P.RDS_Type := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_URI =>
P.URI := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_LOCAL_ID =>
P.Local_Id := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_DELEGATE =>
P.Delegate := Util.Beans.Objects.To_Unbounded_String (Value);
end case;
end Set_Member;
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_PRIORITY =>
return Util.Beans.Objects.To_Object (P.Priority);
when FIELD_TYPE =>
return Util.Beans.Objects.To_Object (P.RDS_Type);
when FIELD_URI =>
return Util.Beans.Objects.To_Object (P.URI);
when FIELD_LOCAL_ID =>
return Util.Beans.Objects.To_Object (P.Local_Id);
when FIELD_DELEGATE =>
return Util.Beans.Objects.To_Object (P.Delegate);
end case;
end Get_Member;
package Service_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Service,
Element_Type_Access => Service_Access,
Fields => Service_Fields,
Set_Member => Set_Member);
package Service_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Service_Vector,
Element_Mapper => Service_Mapper);
procedure Print (P : in Service) is
begin
Ada.Text_IO.Put_Line (" URI: " & To_String (P.URI));
Ada.Text_IO.Put_Line (" Priority: " & Integer'Image (P.Priority));
Ada.Text_IO.Put_Line ("Type (last): " & To_String (P.RDS_Type));
Ada.Text_IO.Put_Line (" Delegate: " & To_String (P.Delegate));
Ada.Text_IO.New_Line;
end Print;
procedure Print (P : in Service_Vector.Cursor) is
begin
Print (Service_Vector.Element (P));
end Print;
Service_Mapping : aliased Service_Mapper.Mapper;
Service_Vector_Mapping : aliased Service_Vector_Mapper.Mapper;
Mapper : Util.Serialize.Mappers.Processing;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: xmlrd file...");
return;
end if;
Service_Mapping.Add_Mapping ("Type", FIELD_TYPE);
Service_Mapping.Add_Mapping ("URI", FIELD_URI);
Service_Mapping.Add_Mapping ("Delegate", FIELD_DELEGATE);
Service_Mapping.Add_Mapping ("@priority", FIELD_PRIORITY);
Service_Mapping.Bind (Get_Member'Access);
Service_Vector_Mapping.Set_Mapping (Service_Mapping'Unchecked_Access);
Mapper.Add_Mapping ("XRDS/XRD/Service", Service_Vector_Mapping'Unchecked_Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Service_Vector_Mapper.Vector;
begin
Service_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access);
Reader.Parse (S, Mapper);
Ada.Text_IO.Put_Line ("Rule count: " & Count_Type'Image (List.Length));
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
declare
Output : Util.Serialize.IO.XML.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Start_Entity ("XRDS");
Service_Vector_Mapping.Write (Output, List);
Output.End_Entity ("XRDS");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Xmlrd;
|
-----------------------------------------------------------------------
-- xrds -- XRDS parser example
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Beans;
with Util.Beans.Objects;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Serialize.IO.XML;
procedure Xmlrd is
use Ada.Containers;
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
Reader : Util.Serialize.IO.XML.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
type Service_Fields is (FIELD_PRIORITY, FIELD_TYPE, FIELD_URI, FIELD_LOCAL_ID, FIELD_DELEGATE);
type Service is record
Priority : Integer;
URI : Ada.Strings.Unbounded.Unbounded_String;
RDS_Type : Ada.Strings.Unbounded.Unbounded_String;
Delegate : Ada.Strings.Unbounded.Unbounded_String;
Local_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Service_Access is access all Service;
package Service_Vector is
new Ada.Containers.Vectors (Element_Type => Service,
Index_Type => Natural);
procedure Print (P : in Service_Vector.Cursor);
procedure Print (P : in Service);
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object);
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object;
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object) is
begin
Ada.Text_IO.Put_Line ("Set member " & Service_Fields'Image (Field)
& " to " & Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_PRIORITY =>
P.Priority := Util.Beans.Objects.To_Integer (Value);
when FIELD_TYPE =>
P.RDS_Type := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_URI =>
P.URI := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_LOCAL_ID =>
P.Local_Id := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_DELEGATE =>
P.Delegate := Util.Beans.Objects.To_Unbounded_String (Value);
end case;
end Set_Member;
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_PRIORITY =>
return Util.Beans.Objects.To_Object (P.Priority);
when FIELD_TYPE =>
return Util.Beans.Objects.To_Object (P.RDS_Type);
when FIELD_URI =>
return Util.Beans.Objects.To_Object (P.URI);
when FIELD_LOCAL_ID =>
return Util.Beans.Objects.To_Object (P.Local_Id);
when FIELD_DELEGATE =>
return Util.Beans.Objects.To_Object (P.Delegate);
end case;
end Get_Member;
package Service_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Service,
Element_Type_Access => Service_Access,
Fields => Service_Fields,
Set_Member => Set_Member);
package Service_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Service_Vector,
Element_Mapper => Service_Mapper);
procedure Print (P : in Service) is
begin
Ada.Text_IO.Put_Line (" URI: " & To_String (P.URI));
Ada.Text_IO.Put_Line (" Priority: " & Integer'Image (P.Priority));
Ada.Text_IO.Put_Line ("Type (last): " & To_String (P.RDS_Type));
Ada.Text_IO.Put_Line (" Delegate: " & To_String (P.Delegate));
Ada.Text_IO.New_Line;
end Print;
procedure Print (P : in Service_Vector.Cursor) is
begin
Print (Service_Vector.Element (P));
end Print;
Service_Mapping : aliased Service_Mapper.Mapper;
Service_Vector_Mapping : aliased Service_Vector_Mapper.Mapper;
Mapper : Util.Serialize.Mappers.Processing;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: xmlrd file...");
return;
end if;
Service_Mapping.Add_Mapping ("Type", FIELD_TYPE);
Service_Mapping.Add_Mapping ("URI", FIELD_URI);
Service_Mapping.Add_Mapping ("Delegate", FIELD_DELEGATE);
Service_Mapping.Add_Mapping ("@priority", FIELD_PRIORITY);
Service_Mapping.Bind (Get_Member'Access);
Service_Vector_Mapping.Set_Mapping (Service_Mapping'Unchecked_Access);
Mapper.Add_Mapping ("XRDS/XRD/Service", Service_Vector_Mapping'Unchecked_Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Service_Vector_Mapper.Vector;
begin
Service_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access);
Reader.Parse (S, Mapper);
Ada.Text_IO.Put_Line ("Rule count: " & Count_Type'Image (List.Length));
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
declare
Buffer : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.XML.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Output.Initialize (Output => Buffer'Unchecked_access);
Output.Start_Entity ("XRDS");
Service_Vector_Mapping.Write (Output, List);
Output.End_Entity ("XRDS");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffer));
end;
end;
end loop;
end Xmlrd;
|
Update the example
|
Update the example
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
30e691cf430fea2625487685d60ff474abfe2df5
|
src/gen-model.adb
|
src/gen-model.adb
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code 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 Ada.Strings.Fixed;
with Ada.Strings.Maps;
with DOM.Core.Nodes;
with Gen.Utils;
package body Gen.Model is
Trim_Chars : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR);
-- ------------------------------
-- Get the object unique name.
-- ------------------------------
function Get_Name (From : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- 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 Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "comment" then
return From.Comment;
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Row_Index);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
else
return From.Attrs.Get_Value (Name);
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.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return String is
V : constant Util.Beans.Objects.Object := From.Get_Value (Name);
begin
return Util.Beans.Objects.To_String (V);
end Get_Attribute;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name));
end Get_Attribute;
-- ------------------------------
-- Set the comment associated with the element.
-- ------------------------------
procedure Set_Comment (Def : in out Definition;
Comment : in String) is
Trimmed_Comment : constant String := Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars);
begin
Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment);
end Set_Comment;
-- ------------------------------
-- Initialize the definition from the DOM node attributes.
-- ------------------------------
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node) is
use type DOM.Core.Node;
Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node);
begin
Def.Name := Name;
Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node));
for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop
declare
A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I);
begin
if A /= null then
declare
Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A);
Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A);
begin
Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end;
end loop;
end Initialize;
end Gen.Model;
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code 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 Ada.Strings.Fixed;
with Ada.Strings.Maps;
with DOM.Core.Nodes;
with Gen.Utils;
package body Gen.Model is
Trim_Chars : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR);
-- ------------------------------
-- Get the object unique name.
-- ------------------------------
function Get_Name (From : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (From.Def_Name);
end Get_Name;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String is
begin
return From.Def_Name;
end Name;
-- ------------------------------
-- Set the object unique name.
-- ------------------------------
procedure Set_Name (Def : in out Definition;
Name : in String) is
begin
Def.Def_Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
end Set_Name;
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Def.Def_Name := Name;
end Set_Name;
-- ------------------------------
-- 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 Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "comment" then
return From.Comment;
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Row_Index);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Def_Name);
else
return From.Attrs.Get_Value (Name);
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.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return String is
V : constant Util.Beans.Objects.Object := From.Get_Value (Name);
begin
return Util.Beans.Objects.To_String (V);
end Get_Attribute;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name));
end Get_Attribute;
-- ------------------------------
-- Set the comment associated with the element.
-- ------------------------------
procedure Set_Comment (Def : in out Definition;
Comment : in String) is
Trimmed_Comment : constant String := Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars);
begin
Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment);
end Set_Comment;
-- ------------------------------
-- Get the comment associated with the element.
-- ------------------------------
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object is
begin
return Def.Comment;
end Get_Comment;
-- ------------------------------
-- Set the location (file and line) where the model element is defined in the XMI file.
-- ------------------------------
procedure Set_Location (Node : in out Definition;
Location : in String) is
begin
Node.Location := Ada.Strings.Unbounded.To_Unbounded_String (Location);
end Set_Location;
-- ------------------------------
-- Get the location file and line where the model element is defined.
-- ------------------------------
function Get_Location (Node : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (Node.Location);
end Get_Location;
-- ------------------------------
-- Initialize the definition from the DOM node attributes.
-- ------------------------------
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node) is
use type DOM.Core.Node;
Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node);
begin
Def.Def_Name := Name;
Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node));
for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop
declare
A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I);
begin
if A /= null then
declare
Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A);
Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A);
begin
Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end;
end loop;
end Initialize;
end Gen.Model;
|
Implement Name, Set_Name, Get_Location, Set_Location, Get_Comment operations
|
Implement Name, Set_Name, Get_Location, Set_Location, Get_Comment operations
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
94ef96b58642a09fcbbe9a5d1b71dbd3ba400bd1
|
src/gl/interface/gl-algebra.ads
|
src/gl/interface/gl-algebra.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
generic
type Element_Type is private;
type Index_Type is (<>);
package GL.Algebra is
pragma Pure;
-----------------------------------------------------------------------------
-- Vector types --
-----------------------------------------------------------------------------
type Vector2 is array (Index_2D) of aliased Element_Type;
type Vector3 is array (Index_3D) of aliased Element_Type;
type Vector4 is array (Index_Homogeneous) of aliased Element_Type;
pragma Convention (C, Vector2);
pragma Convention (C, Vector3);
pragma Convention (C, Vector4);
-----------------------------------------------------------------------------
-- Matrix types --
-----------------------------------------------------------------------------
type Matrix2 is array (Index_2D, Index_2D) of aliased Element_Type;
type Matrix3 is array (Index_3D, Index_3D) of aliased Element_Type;
type Matrix4 is array (Index_Homogeneous, Index_Homogeneous) of aliased Element_Type;
pragma Convention (C, Matrix2);
pragma Convention (C, Matrix3);
pragma Convention (C, Matrix4);
-----------------------------------------------------------------------------
-- Array types --
-----------------------------------------------------------------------------
type Vector2_Array is array (Index_Type range <>) of aliased Vector2;
type Vector3_Array is array (Index_Type range <>) of aliased Vector3;
type Vector4_Array is array (Index_Type range <>) of aliased Vector4;
type Matrix2_Array is array (Index_Type range <>) of aliased Matrix2;
type Matrix3_Array is array (Index_Type range <>) of aliased Matrix3;
type Matrix4_Array is array (Index_Type range <>) of aliased Matrix4;
pragma Convention (C, Vector2_Array);
pragma Convention (C, Vector3_Array);
pragma Convention (C, Vector4_Array);
pragma Convention (C, Matrix2_Array);
pragma Convention (C, Matrix3_Array);
pragma Convention (C, Matrix4_Array);
end GL.Algebra;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
generic
type Element_Type is private;
type Index_Type is (<>);
package GL.Algebra is
pragma Pure;
-----------------------------------------------------------------------------
-- Vector types --
-----------------------------------------------------------------------------
type Vector2 is array (Index_2D) of aliased Element_Type;
type Vector3 is array (Index_3D) of aliased Element_Type;
type Vector4 is array (Index_Homogeneous) of aliased Element_Type;
pragma Convention (C, Vector2);
pragma Convention (C, Vector3);
pragma Convention (C, Vector4);
-----------------------------------------------------------------------------
-- Matrix types --
-----------------------------------------------------------------------------
type Matrix4 is array (Index_Homogeneous, Index_Homogeneous) of aliased Element_Type;
pragma Convention (C, Matrix4);
-----------------------------------------------------------------------------
-- Array types --
-----------------------------------------------------------------------------
type Vector2_Array is array (Index_Type range <>) of aliased Vector2;
type Vector3_Array is array (Index_Type range <>) of aliased Vector3;
type Vector4_Array is array (Index_Type range <>) of aliased Vector4;
type Matrix4_Array is array (Index_Type range <>) of aliased Matrix4;
pragma Convention (C, Vector2_Array);
pragma Convention (C, Vector3_Array);
pragma Convention (C, Vector4_Array);
pragma Convention (C, Matrix4_Array);
end GL.Algebra;
|
Remove unused matrix types in GL.Algebra
|
gl: Remove unused matrix types in GL.Algebra
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
c8505b3a66efc218809c13d866cf4429e3f56c0a
|
src/security-oauth-clients.adb
|
src/security-oauth-clients.adb
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
with Util.Log.Loggers;
with Util.Strings;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Encoders.HMAC.SHA1;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package body Security.OAuth.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
-- ------------------------------
-- Access Token
-- ------------------------------
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
protected type Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array);
private
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
-- Number of 32-bit random numbers used for the ID generation.
Id_Size : Ada.Streams.Stream_Element_Offset := 8;
end Random;
protected body Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
begin
-- Generate the random sequence.
for I in 0 .. Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Into (4 * I) := Stream_Element (Value and 16#0FF#);
Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate;
end Random;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the application identifier.
-- ------------------------------
function Get_Application_Identifier (App : in Application) return String is
begin
return Ada.Strings.Unbounded.To_String (App.Client_Id);
end Get_Application_Identifier;
-- ------------------------------
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
-- ------------------------------
procedure Set_Application_Identifier (App : in out Application;
Client : in String) is
use Ada.Strings.Unbounded;
begin
App.Client_Id := To_Unbounded_String (Client);
App.Protect := App.Client_Id & App.Callback;
end Set_Application_Identifier;
-- ------------------------------
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
-- ------------------------------
procedure Set_Application_Secret (App : in out Application;
Secret : in String) is
begin
App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret);
App.Key := App.Secret;
end Set_Application_Secret;
-- ------------------------------
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
-- ------------------------------
procedure Set_Application_Callback (App : in out Application;
URI : in String) is
use Ada.Strings.Unbounded;
begin
App.Callback := To_Unbounded_String (URI);
App.Protect := App.Client_Id & App.Callback;
end Set_Application_Callback;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
use Ada.Strings.Unbounded;
Data : constant String := Nonce & To_String (App.Protect);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.Client_Id
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Redirect_Uri
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Scope
& "=" & Scope
& "&"
& Security.OAuth.State
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.Grant_Type & "=authorization_code"
& "&"
& Security.OAuth.Code & "=" & Code
& "&"
& Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
with Util.Log.Loggers;
with Util.Strings;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Encoders.Base64;
with Util.Encoders.HMAC.SHA1;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package body Security.OAuth.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
-- ------------------------------
-- Access Token
-- ------------------------------
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
protected type Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array);
private
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
end Random;
protected body Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Ada.Streams.Stream_Element_Offset := Into'Last / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Into (4 * I) := Stream_Element (Value and 16#0FF#);
Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate;
end Random;
Random_Generator : Random;
-- ------------------------------
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
-- ------------------------------
function Create_Nonce (Bits : in Positive := 256) return String is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Random_Generator.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
declare
Result : String (1 .. Natural (Encoded + 1));
begin
for I in 0 .. Encoded loop
Result (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
return Result;
end;
end Create_Nonce;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the application identifier.
-- ------------------------------
function Get_Application_Identifier (App : in Application) return String is
begin
return Ada.Strings.Unbounded.To_String (App.Client_Id);
end Get_Application_Identifier;
-- ------------------------------
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
-- ------------------------------
procedure Set_Application_Identifier (App : in out Application;
Client : in String) is
use Ada.Strings.Unbounded;
begin
App.Client_Id := To_Unbounded_String (Client);
App.Protect := App.Client_Id & App.Callback;
end Set_Application_Identifier;
-- ------------------------------
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
-- ------------------------------
procedure Set_Application_Secret (App : in out Application;
Secret : in String) is
begin
App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret);
App.Key := App.Secret;
end Set_Application_Secret;
-- ------------------------------
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
-- ------------------------------
procedure Set_Application_Callback (App : in out Application;
URI : in String) is
use Ada.Strings.Unbounded;
begin
App.Callback := To_Unbounded_String (URI);
App.Protect := App.Client_Id & App.Callback;
end Set_Application_Callback;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
use Ada.Strings.Unbounded;
Data : constant String := Nonce & To_String (App.Protect);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.Client_Id
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Redirect_Uri
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Scope
& "=" & Scope
& "&"
& Security.OAuth.State
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.Grant_Type & "=authorization_code"
& "&"
& Security.OAuth.Code & "=" & Code
& "&"
& Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
Implement the Create_Nonce by using a random generator and converting the result into base64url
|
Implement the Create_Nonce by using a random generator and converting the result into base64url
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
52db4aad31c189b30b21d51937ed535759d213fc
|
awa/src/awa-applications.ads
|
awa/src/awa-applications.ads
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified before the application modules.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified after all the application modules
-- are initialized.
package P_Plugin_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", "");
-- The database connection string to connect to the database.
package P_Database is
new ASF.Applications.Main.Configs.Parameter ("database",
"mysql://localhost:3306/db");
-- The application contextPath configuration that gives the base URL of the application.
package P_Context_Path is
new ASF.Applications.Main.Configs.Parameter ("contextPath",
"");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- 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);
-- 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);
-- 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);
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
procedure Load_Configuration (App : in out Application;
Files : in String);
-- 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.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container when the server is started.
overriding
procedure Start (App : in out Application);
-- Close the application.
overriding
procedure Close (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
end record;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa-applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 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 Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
with AWA.Audits.Services;
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified before the application modules.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified after all the application modules
-- are initialized.
package P_Plugin_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", "");
-- The database connection string to connect to the database.
package P_Database is
new ASF.Applications.Main.Configs.Parameter ("database",
"mysql://localhost:3306/db");
-- The application contextPath configuration that gives the base URL of the application.
package P_Context_Path is
new ASF.Applications.Main.Configs.Parameter ("contextPath",
"");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- 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);
-- 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);
-- 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);
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
procedure Load_Configuration (App : in out Application;
Files : in String);
-- 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.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container when the server is started.
overriding
procedure Start (App : in out Application);
-- Close the application.
overriding
procedure Close (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
Audits : aliased AWA.Audits.Services.Audit_Manager;
end record;
end AWA.Applications;
|
Declare an instance of the Audit manager for the application
|
Declare an instance of the Audit manager for the application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1935e17042c63884b84f527e783a4dac9a53e77d
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with AWA.Tests;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("The page");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P);
end Test_Create_Wiki_Page;
end AWA.Wikis.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with AWA.Tests;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("The page");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("The page");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P);
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
end AWA.Wikis.Modules.Tests;
|
Implement the Test_Create_Wiki_Content unit test for the wiki content creation
|
Implement the Test_Create_Wiki_Content unit test for the wiki content creation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0d145a667cf8594c0a0f4a97fbb69eaed5ca44a4
|
awa/regtests/awa-mail-clients-tests.adb
|
awa/regtests/awa-mail-clients-tests.adb
|
-----------------------------------------------------------------------
-- awa-mail-clients-tests -- Unit tests for Mail clients
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Properties;
package body AWA.Mail.Clients.Tests is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Manager'Class,
Name => AWA.Mail.Clients.Mail_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class,
Name => AWA.Mail.Clients.Mail_Message_Access);
package Caller is new Util.Test_Caller (Test, "Mail.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Mail.Clients.Factory",
Test_Factory'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Clients.Create_Message",
Test_Create_Message'Access);
end Add_Tests;
-- ------------------------------
-- Test the mail manager factory.
-- ------------------------------
procedure Test_Factory (T : in out Test) is
M : AWA.Mail.Clients.Mail_Manager_Access;
P : Util.Properties.Manager;
begin
M := AWA.Mail.Clients.Factory ("file", P);
T.Assert (M /= null, "Factory returned a null mail manager");
Free (M);
M := AWA.Mail.Clients.Factory ("something", P);
T.Assert (M = null, "Factory returned a non null mail manager");
end Test_Factory;
-- ------------------------------
-- Create an email message and verify its content.
-- ------------------------------
procedure Test_Create_Message (T : in out Test) is
procedure Send;
M : AWA.Mail.Clients.Mail_Manager_Access;
procedure Send is
Msg : AWA.Mail.Clients.Mail_Message_Access := M.Create_Message;
begin
Msg.Set_From (Name => "Iorek Byrnison", Address => "[email protected]");
Msg.Add_Recipient (Kind => TO, Name => "Tous les ours", Address => "[email protected]");
Msg.Set_Subject (Subject => "Decret");
Msg.Set_Body (Content => "Le palais doit etre debarasse des fantaisies humaines.");
Msg.Send;
Free (Msg);
end Send;
begin
M := AWA.Mail.Clients.Factory ("file", Util.Tests.Get_Properties);
T.Assert (M /= null, "Factory returned a null mail manager");
for I in 1 .. 10 loop
Send;
end loop;
Free (M);
-- The SMTP mailer could be disabled from the configuration.
M := AWA.Mail.Clients.Factory ("smtp", Util.Tests.Get_Properties);
if M /= null then
for I in 1 .. 10 loop
Send;
end loop;
Free (M);
end if;
end Test_Create_Message;
end AWA.Mail.Clients.Tests;
|
-----------------------------------------------------------------------
-- awa-mail-clients-tests -- Unit tests for Mail clients
-- Copyright (C) 2012, 2013, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Properties;
package body AWA.Mail.Clients.Tests is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Manager'Class,
Name => AWA.Mail.Clients.Mail_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class,
Name => AWA.Mail.Clients.Mail_Message_Access);
package Caller is new Util.Test_Caller (Test, "Mail.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Mail.Clients.Factory",
Test_Factory'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Clients.Create_Message",
Test_Create_Message'Access);
end Add_Tests;
-- ------------------------------
-- Test the mail manager factory.
-- ------------------------------
procedure Test_Factory (T : in out Test) is
M : AWA.Mail.Clients.Mail_Manager_Access;
P : Util.Properties.Manager;
begin
M := AWA.Mail.Clients.Factory ("file", P);
T.Assert (M /= null, "Factory returned a null mail manager");
Free (M);
M := AWA.Mail.Clients.Factory ("something", P);
T.Assert (M = null, "Factory returned a non null mail manager");
end Test_Factory;
-- ------------------------------
-- Create an email message and verify its content.
-- ------------------------------
procedure Test_Create_Message (T : in out Test) is
procedure Send;
M : AWA.Mail.Clients.Mail_Manager_Access;
procedure Send is
Msg : AWA.Mail.Clients.Mail_Message_Access := M.Create_Message;
C : Ada.Strings.Unbounded.Unbounded_String;
begin
Append (C, "Le palais doit etre debarasse des fantaisies humaines.");
Msg.Set_From (Name => "Iorek Byrnison", Address => "[email protected]");
Msg.Add_Recipient (Kind => TO, Name => "Tous les ours", Address => "[email protected]");
Msg.Set_Subject (Subject => "Decret");
Msg.Set_Body (Content => C, Alternative => C);
Msg.Send;
Free (Msg);
end Send;
begin
M := AWA.Mail.Clients.Factory ("file", Util.Tests.Get_Properties);
T.Assert (M /= null, "Factory returned a null mail manager");
for I in 1 .. 10 loop
Send;
end loop;
Free (M);
-- The SMTP mailer could be disabled from the configuration.
M := AWA.Mail.Clients.Factory ("smtp", Util.Tests.Get_Properties);
if M /= null then
for I in 1 .. 10 loop
Send;
end loop;
Free (M);
end if;
end Test_Create_Message;
end AWA.Mail.Clients.Tests;
|
Update the mail unit test
|
Update the mail unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3f0fe946d921dda68cd121d8a7dcf4889391917c
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report");
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "1000 Log.Info message (output)");
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "10000 Log.Debug message (no output)");
end;
end Test_Log_Perf;
-- Test appending the log on several log files
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report");
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "1000 Log.Info message (output)");
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "10000 Log.Debug message (no output)");
end;
end Test_Log_Perf;
-- Test appending the log on several log files
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Update test after removal of a debug log message in Util.Log.Loggers.Finalize
|
Update test after removal of a debug log message in Util.Log.Loggers.Finalize
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
baf848a55e941630e3849ea30f44caec272c0544
|
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"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
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
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
pragma Unreferenced (Realm);
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
pragma Unreferenced (Realm, OP);
begin
Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128));
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Use Create_Nonce for the nonce generation Fix compilation warnings
|
Use Create_Nonce for the nonce generation
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
828c1e03838f9bf40cf4fb2f939cb457b9702a88
|
src/babel_main.adb
|
src/babel_main.adb
|
with GNAT.IO; use GNAT.IO;
with Babel;
with Babel.Files;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Encoders;
with Util.Encoders.Base16;
with Babel.Filters;
with Babel.Files.Buffers;
with Babel.Stores.Local;
with Babel.Strategies.Default;
with Babel.Strategies.Workers;
procedure babel_main is
use Ada.Strings.Unbounded;
Dir : Babel.Files.Directory;
Hex_Encoder : Util.Encoders.Base16.Encoder;
Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type;
Local : aliased Babel.Stores.Local.Local_Store_Type;
Backup : aliased Babel.Strategies.Default.Default_Strategy_Type;
Buffers : aliased Babel.Files.Buffers.Buffer_Pools.Pool;
procedure Print_Sha (Path : in String;
File : in out Babel.Files.File) is
Sha : constant String := Hex_Encoder.Transform (File.SHA1);
begin
Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha);
end Print_Sha;
procedure Do_Backup (Count : in Positive) is
Workers : Babel.Strategies.Workers.Worker_Type (Count);
begin
Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access);
Backup.Scan (".");
end Do_Backup;
begin
Exclude.Add_Exclude (".svn");
Exclude.Add_Exclude ("obj");
Babel.Files.Buffers.Create_Pool (Buffers, 10, 1_000_000);
Backup.Set_Filters (Exclude'Unchecked_Access);
Backup.Set_Stores (Local'Unchecked_Access, Local'Unchecked_Access);
Backup.Set_Buffers (Buffers'Unchecked_Access);
Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size));
Do_Backup (2);
-- Bkp.Files.Scan (".", Dir);
-- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access);
Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size));
Put_Line ("File count: " & Natural'Image (Dir.Tot_Files));
Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs));
end babel_main;
|
with GNAT.IO; use GNAT.IO;
with Babel;
with Babel.Files;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Encoders;
with Util.Encoders.Base16;
with Babel.Filters;
with Babel.Files.Buffers;
with Babel.Stores.Local;
with Babel.Strategies.Default;
with Babel.Strategies.Workers;
procedure babel_main is
use Ada.Strings.Unbounded;
Dir : Babel.Files.Directory_Type;
Hex_Encoder : Util.Encoders.Base16.Encoder;
Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type;
Local : aliased Babel.Stores.Local.Local_Store_Type;
Backup : aliased Babel.Strategies.Default.Default_Strategy_Type;
Buffers : aliased Babel.Files.Buffers.Buffer_Pools.Pool;
Store : aliased Babel.Stores.Local.Local_Store_Type;
--
-- procedure Print_Sha (Path : in String;
-- File : in out Babel.Files.File) is
-- Sha : constant String := Hex_Encoder.Transform (File.SHA1);
-- begin
-- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha);
-- end Print_Sha;
procedure Do_Backup (Count : in Positive) is
Workers : Babel.Strategies.Workers.Worker_Type (Count);
begin
Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access);
Backup.Scan (".");
end Do_Backup;
begin
Exclude.Add_Exclude (".svn");
Exclude.Add_Exclude ("obj");
Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000);
Store.Set_Root_Directory ("/tmp/babel-store");
Local.Set_Root_Directory (".");
Backup.Set_Filters (Exclude'Unchecked_Access);
Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access);
Backup.Set_Buffers (Buffers'Unchecked_Access);
Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size));
Do_Backup (2);
-- Bkp.Files.Scan (".", Dir);
-- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access);
-- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size));
-- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files));
-- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs));
end babel_main;
|
Update and remove some old code
|
Update and remove some old code
|
Ada
|
apache-2.0
|
stcarrez/babel
|
c8914f93b6d2ecba43f88734fd2066409aeaf419
|
regtests/ado-statements-tests.adb
|
regtests/ado-statements-tests.adb
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with ADO.Sessions;
with Regtests.Statements.Model;
package body ADO.Statements.Tests is
use Util.Tests;
procedure Populate (Tst : in out Test);
function Get_Sum (T : in Test;
Table : in String) return Natural;
-- Test the query statement Get_Xxx operation for various types.
generic
type T (<>) is private;
with function Get_Value (Stmt : in ADO.Statements.Query_Statement;
Column : in Natural) return T is <>;
Name : String;
Column : String;
procedure Test_Query_Get_Value_T (Tst : in out Test);
procedure Populate (Tst : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
Tst.Assert (Item.Is_Inserted, "Item inserted in database");
end;
end loop;
DB.Commit;
end Populate;
-- ------------------------------
-- Test the query statement Get_Xxx operation for various types.
-- ------------------------------
procedure Test_Query_Get_Value_T (Tst : in out Test) is
Stmt : ADO.Statements.Query_Statement;
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
begin
Populate (Tst);
-- Check that Get_Value raises an exception if the statement is invalid.
begin
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name);
end;
exception
when Invalid_Statement =>
null;
end;
-- Execute a query to fetch one column.
Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1");
Stmt.Execute;
-- Verify the query result and the Get_Value operation.
Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for "
& Name & ":" & Column);
Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for "
& Name & ":" & Column);
Util.Tests.Assert_Equals (Tst, Column,
Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)),
"The query returns an invalid column name");
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Stmt.Clear;
end;
end Test_Query_Get_Value_T;
procedure Test_Query_Get_Int64 is
new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value");
procedure Test_Query_Get_Integer is
new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value");
procedure Test_Query_Get_Nullable_Integer is
new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer,
"Get_Nullable_Integer", "int_value");
procedure Test_Query_Get_Nullable_Entity_Type is
new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type,
"Get_Nullable_Entity_Type", "entity_value");
procedure Test_Query_Get_Natural is
new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value");
procedure Test_Query_Get_Identifier is
new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier,
"Get_Identifier", "id_value");
procedure Test_Query_Get_Boolean is
new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value");
procedure Test_Query_Get_String is
new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value");
package Caller is new Util.Test_Caller (Test, "ADO.Statements");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Statements.Save",
Test_Save'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64",
Test_Query_Get_Int64'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer",
Test_Query_Get_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer",
Test_Query_Get_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural",
Test_Query_Get_Natural'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier",
Test_Query_Get_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean",
Test_Query_Get_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_String",
Test_Query_Get_String'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type",
Test_Query_Get_Nullable_Entity_Type'Access);
end Add_Tests;
function Get_Sum (T : in Test;
Table : in String) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table);
begin
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
-- Util.Tests.Assert_Equals (T, 1, Stmt.Get_Row_Count, "The query must return one row "
-- & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
-- ------------------------------
-- Test creation of several rows in test_table with different column type.
-- ------------------------------
procedure Test_Save (T : in out Test) is
First : constant Natural := Get_Sum (T, "test_table");
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
end;
end loop;
DB.Commit;
Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"),
"The SUM query returns an invalid value for test_table");
end Test_Save;
end ADO.Statements.Tests;
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with ADO.Utils;
with ADO.Sessions;
with Regtests.Statements.Model;
package body ADO.Statements.Tests is
use Util.Tests;
procedure Populate (Tst : in out Test);
function Get_Sum (T : in Test;
Table : in String) return Natural;
-- Test the query statement Get_Xxx operation for various types.
generic
type T (<>) is private;
with function Get_Value (Stmt : in ADO.Statements.Query_Statement;
Column : in Natural) return T is <>;
Name : String;
Column : String;
procedure Test_Query_Get_Value_T (Tst : in out Test);
procedure Populate (Tst : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
Tst.Assert (Item.Is_Inserted, "Item inserted in database");
end;
end loop;
DB.Commit;
end Populate;
-- ------------------------------
-- Test the query statement Get_Xxx operation for various types.
-- ------------------------------
procedure Test_Query_Get_Value_T (Tst : in out Test) is
Stmt : ADO.Statements.Query_Statement;
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
begin
Populate (Tst);
-- Check that Get_Value raises an exception if the statement is invalid.
begin
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name);
end;
exception
when Invalid_Statement =>
null;
end;
-- Execute a query to fetch one column.
Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1");
Stmt.Execute;
-- Verify the query result and the Get_Value operation.
Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for "
& Name & ":" & Column);
Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for "
& Name & ":" & Column);
Util.Tests.Assert_Equals (Tst, Column,
Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)),
"The query returns an invalid column name");
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Stmt.Clear;
end;
end Test_Query_Get_Value_T;
procedure Test_Query_Get_Int64 is
new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value");
procedure Test_Query_Get_Integer is
new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value");
procedure Test_Query_Get_Nullable_Integer is
new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer,
"Get_Nullable_Integer", "int_value");
procedure Test_Query_Get_Nullable_Entity_Type is
new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type,
"Get_Nullable_Entity_Type", "entity_value");
procedure Test_Query_Get_Natural is
new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value");
procedure Test_Query_Get_Identifier is
new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier,
"Get_Identifier", "id_value");
procedure Test_Query_Get_Boolean is
new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value");
procedure Test_Query_Get_String is
new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value");
package Caller is new Util.Test_Caller (Test, "ADO.Statements");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Statements.Save",
Test_Save'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64",
Test_Query_Get_Int64'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer",
Test_Query_Get_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer",
Test_Query_Get_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural",
Test_Query_Get_Natural'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier",
Test_Query_Get_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean",
Test_Query_Get_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_String",
Test_Query_Get_String'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type",
Test_Query_Get_Nullable_Entity_Type'Access);
end Add_Tests;
function Get_Sum (T : in Test;
Table : in String) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table);
begin
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
function Get_Sum (T : in Test;
Table : in String;
Ids : in ADO.Utils.Identifier_Vector) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table
& " WHERE id IN (:ids)");
begin
Stmt.Bind_Param ("ids", Ids);
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
-- ------------------------------
-- Test creation of several rows in test_table with different column type.
-- ------------------------------
procedure Test_Save (T : in out Test) is
First : constant Natural := Get_Sum (T, "test_table");
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
List : ADO.Utils.Identifier_Vector;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
List.Append (Item.Get_Id);
end;
end loop;
DB.Commit;
Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"),
"The SUM query returns an invalid value for test_table");
Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List),
"The SUM query returns an invalid value for test_table");
end Test_Save;
end ADO.Statements.Tests;
|
Update the tests to also use ADO.Utils.Identifier_Vector and verify the string conversion
|
Update the tests to also use ADO.Utils.Identifier_Vector and verify the string conversion
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
a76c6a7b40a5c16c3a29f3c18db6a480ea3b7f95
|
src/babel-strategies.adb
|
src/babel-strategies.adb
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Files.Lifecycles;
with Babel.Stores;
package body Babel.Strategies is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies");
-- ------------------------------
-- Allocate a buffer to read the file content.
-- ------------------------------
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is
Result : Babel.Files.Buffers.Buffer_Access;
begin
Strategy.Buffers.Get_Instance (Result);
return Result;
end Allocate_Buffer;
-- ------------------------------
-- Release the buffer that was allocated by Allocate_Buffer.
-- ------------------------------
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access) is
begin
Strategy.Buffers.Release (Buffer);
Buffer := null;
end Release_Buffer;
-- ------------------------------
-- Set the buffer pool to be used by Allocate_Buffer.
-- ------------------------------
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Strategy.Buffers := Buffers;
end Set_Buffers;
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Read_Store.Read (Path, Into.all);
end Read_File;
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Write_Store.Write (Path, Content.all);
end Write_File;
procedure Print_Sha (File : in Babel.Files.File_Type) is
Sha : constant String := Babel.Files.Get_SHA1 (File);
begin
Log.Info (Babel.Files.Get_Path (File) & " => " & Sha);
end Print_Sha;
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access) is
begin
if Babel.Files.Is_New (File) then
Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File);
else
Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File);
end if;
Print_Sha (File);
Strategy.Write_File (File, Content);
Strategy.Release_Buffer (Content);
end Backup_File;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class) is
Path : constant String := Babel.Files.Get_Path (Directory);
begin
Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all);
end Scan;
-- ------------------------------
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
-- ------------------------------
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class) is
procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is
begin
Babel.Files.Queues.Add_Directory (Queue, Directory);
end Append_Directory;
Dir : Babel.Files.Directory_Type;
begin
while Babel.Files.Queues.Has_Directory (Queue) loop
Babel.Files.Queues.Peek_Directory (Queue, Dir);
Container.Set_Directory (Dir);
Strategy_Type'Class (Strategy).Scan (Dir, Container);
Container.Each_Directory (Append_Directory'Access);
end loop;
end Scan;
-- ------------------------------
-- Set the file filters that will be used when scanning the read store.
-- ------------------------------
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access) is
begin
Strategy.Filters := Filters;
end Set_Filters;
-- ------------------------------
-- Set the read and write stores that the strategy will use.
-- ------------------------------
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access) is
begin
Strategy.Read_Store := Read;
Strategy.Write_Store := Write;
end Set_Stores;
-- ------------------------------
-- Set the listeners to inform about changes.
-- ------------------------------
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List) is
begin
Strategy.Listeners := Listeners;
end Set_Listeners;
-- ------------------------------
-- Set the database for use by the strategy.
-- ------------------------------
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access) is
begin
Strategy.Database := Database;
end Set_Database;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Files.Lifecycles;
with Babel.Stores;
package body Babel.Strategies is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies");
-- ------------------------------
-- Allocate a buffer to read the file content.
-- ------------------------------
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is
Result : Babel.Files.Buffers.Buffer_Access;
begin
Strategy.Buffers.Get_Instance (Result);
return Result;
end Allocate_Buffer;
-- ------------------------------
-- Release the buffer that was allocated by Allocate_Buffer.
-- ------------------------------
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access) is
begin
Strategy.Buffers.Release (Buffer);
Buffer := null;
end Release_Buffer;
-- ------------------------------
-- Set the buffer pool to be used by Allocate_Buffer.
-- ------------------------------
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Strategy.Buffers := Buffers;
end Set_Buffers;
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Read_Store.Read (Path, Into.all);
end Read_File;
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access) is
Path : constant String := Babel.Files.Get_Path (File);
begin
Strategy.Write_Store.Write (Path, Content.all);
end Write_File;
procedure Print_Sha (File : in Babel.Files.File_Type) is
Sha : constant String := Babel.Files.Get_SHA1 (File);
begin
Log.Info (Babel.Files.Get_Path (File) & " => " & Sha);
end Print_Sha;
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access) is
begin
Strategy.Database.Insert (File);
if Strategy.Listeners /= null then
if Babel.Files.Is_New (File) then
Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File);
else
Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File);
end if;
end if;
Print_Sha (File);
Strategy.Write_File (File, Content);
Strategy.Release_Buffer (Content);
end Backup_File;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class) is
Path : constant String := Babel.Files.Get_Path (Directory);
begin
Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all);
end Scan;
-- ------------------------------
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
-- ------------------------------
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class) is
procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is
begin
Babel.Files.Queues.Add_Directory (Queue, Directory);
end Append_Directory;
Dir : Babel.Files.Directory_Type;
begin
while Babel.Files.Queues.Has_Directory (Queue) loop
Babel.Files.Queues.Peek_Directory (Queue, Dir);
Container.Set_Directory (Dir);
Strategy_Type'Class (Strategy).Scan (Dir, Container);
Container.Each_Directory (Append_Directory'Access);
end loop;
end Scan;
-- ------------------------------
-- Set the file filters that will be used when scanning the read store.
-- ------------------------------
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access) is
begin
Strategy.Filters := Filters;
end Set_Filters;
-- ------------------------------
-- Set the read and write stores that the strategy will use.
-- ------------------------------
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access) is
begin
Strategy.Read_Store := Read;
Strategy.Write_Store := Write;
end Set_Stores;
-- ------------------------------
-- Set the listeners to inform about changes.
-- ------------------------------
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List) is
begin
Strategy.Listeners := Listeners;
end Set_Listeners;
-- ------------------------------
-- Set the database for use by the strategy.
-- ------------------------------
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access) is
begin
Strategy.Database := Database;
end Set_Database;
end Babel.Strategies;
|
Insert the file in the database when the backup is proceeding
|
Insert the file in the database when the backup is proceeding
|
Ada
|
apache-2.0
|
stcarrez/babel
|
10fbc41bbc72135d411a93070b32cfbb4abc1812
|
src/ado-sessions-factory.ads
|
src/ado-sessions-factory.ads
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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.Finalization;
with ADO.Databases;
with ADO.Schemas.Entities;
with ADO.Sequences;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package ADO.Sessions.Factory is
pragma Elaborate_Body;
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
function Get_Session (Proxy : in Session_Proxy_Access) return Session;
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record -- new Ada.Finalization.Limited_Controlled with record
Source : ADO.Databases.DataSource;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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 ADO.Databases;
with ADO.Schemas.Entities;
with ADO.Sequences;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package ADO.Sessions.Factory is
pragma Elaborate_Body;
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
function Get_Session (Proxy : in Session_Proxy_Access) return Session;
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record
Source : ADO.Databases.DataSource;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
2a01f453eeb80ef1d12778e88a073c2a60dc0760
|
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
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
ff6f791f57b6d1980d79acc30b3e8efb4ee9875f
|
src/asf-servlets-mappers.adb
|
src/asf-servlets-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 0 .. Last - 1 loop
N.URL_Patterns.Query_Element (Natural (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Override_Context
or else String '(N.Handler.all.Get_Init_Parameter (Name)) = ""
then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 1 .. Last - 1 loop
N.URL_Patterns.Query_Element (Positive (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Override_Context
or else String '(N.Handler.all.Get_Init_Parameter (Name)) = ""
then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
Fix iteration over url patterns
|
Fix iteration over url patterns
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2b85ac653065f43c7f464502ee80102d2765aeb7
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- 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 Util.Encoders.Base64;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
use Interfaces;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Lock.Write;
-- Generate the random sequence.
for I in 0 .. Factory.Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Factory.Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
Factory.Lock.Release_Write;
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access := new Session_Record;
begin
Impl.Ref_Counter := Util.Concurrent.Counters.ONE;
Impl.Create_Time := Ada.Calendar.Clock;
Impl.Access_Time := Impl.Create_Time;
Impl.Max_Inactive := Factory.Max_Inactive;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Lock.Write;
Factory.Sessions.Insert (Impl.Id.all'Access, Sess);
Factory.Lock.Release_Write;
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Null_Session;
Factory.Lock.Read;
declare
Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
Result := Session_Maps.Element (Pos);
end if;
end;
Factory.Lock.Release_Read;
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Id_Random.Reset (Factory.Random);
end Initialize;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- 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 Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
use Interfaces;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Lock.Write;
-- Generate the random sequence.
for I in 0 .. Factory.Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Factory.Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
Factory.Lock.Release_Write;
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access := new Session_Record;
begin
Impl.Ref_Counter := Util.Concurrent.Counters.ONE;
Impl.Create_Time := Ada.Calendar.Clock;
Impl.Access_Time := Impl.Create_Time;
Impl.Max_Inactive := Factory.Max_Inactive;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Lock.Write;
Factory.Sessions.Insert (Impl.Id.all'Access, Sess);
Factory.Lock.Release_Write;
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Null_Session;
Factory.Lock.Read;
declare
Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
Result := Session_Maps.Element (Pos);
end if;
end;
Factory.Lock.Release_Read;
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Id_Random.Reset (Factory.Random);
end Initialize;
end ASF.Sessions.Factory;
|
Add logs on servlet session to help in fixing session issues in applications
|
Add logs on servlet session to help in fixing session issues in applications
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b8142102bb9b3e3db2789803aa7a21cd049af3a5
|
src/gen-commands-project.ads
|
src/gen-commands-project.ads
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 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.
-----------------------------------------------------------------------
package Gen.Commands.Project is
-- ------------------------------
-- Generator Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- 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);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Project is
-- ------------------------------
-- Generator Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- 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);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Project;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
09921e0a7e201f9a8c8024c64260f9938053f74b
|
src/gen-commands-propset.adb
|
src/gen-commands-propset.adb
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
package body Gen.Commands.Propset is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name);
use Ada.Strings.Unbounded;
begin
if Args.Get_Count /= 2 then
Cmd.Usage;
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUEE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
package body Gen.Commands.Propset is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name);
use Ada.Strings.Unbounded;
begin
if Args.Get_Count /= 2 then
Cmd.Usage;
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
Fix help message for the propset command
|
Fix help message for the propset command
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
2e6e3b919ee07a3fa2c9c0885332be595f55cad2
|
src/http/curl/util-http-clients-curl.ads
|
src/http/curl/util-http-clients-curl.ads
|
-----------------------------------------------------------------------
-- util-http-clients-curl -- HTTP Clients with CURL
-- Copyright (C) 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.Strings.Unbounded;
with Util.Http.Mockups;
package Util.Http.Clients.Curl is
-- Register the CURL Http manager.
procedure Register;
private
package C renames Interfaces.C;
package Strings renames Interfaces.C.Strings;
use type C.size_t;
use type C.int;
-- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due
-- to Eclipse capitalization.
subtype Int is C.int;
subtype Chars_Ptr is Strings.chars_ptr;
subtype Size_T is C.size_t;
subtype CURL is System.Address;
type CURL_Code is new Interfaces.C.int;
CURLE_OK : constant CURL_Code := 0;
type CURL_Info is new Int;
type Curl_Option is new Int;
type CURL_Slist;
type CURL_Slist_Access is access CURL_Slist;
type CURL_Slist is record
Data : Chars_Ptr;
Next : CURL_Slist_Access;
end record;
-- Check the CURL result code and report and exception and a log message if
-- the CURL code indicates an error.
procedure Check_Code (Code : in CURL_Code;
Message : in String);
type Curl_Http_Manager is new Http_Manager with null record;
type Curl_Http_Manager_Access is access all Http_Manager'Class;
-- Create a new HTTP request associated with the current request manager.
procedure Create (Manager : in Curl_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Delete (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in Curl_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record
Data : CURL := System.Null_Address;
URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Curl_Headers : CURL_Slist_Access := null;
end record;
type Curl_Http_Request_Access is access all Curl_Http_Request'Class;
-- Prepare to setup the headers in the request.
procedure Set_Headers (Request : in out Curl_Http_Request);
overriding
procedure Finalize (Request : in out Curl_Http_Request);
type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record
C : CURL;
Content : Ada.Strings.Unbounded.Unbounded_String;
Status : Natural;
Parsing_Body : Boolean := False;
end record;
type Curl_Http_Response_Access is access all Curl_Http_Response'Class;
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Curl_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Curl_Http_Response) return Natural;
-- Add a string to a CURL slist.
function Curl_Slist_Append (List : in CURL_Slist_Access;
Value : in Chars_Ptr) return CURL_Slist_Access;
pragma Import (C, Curl_Slist_Append, "curl_slist_append");
-- Free an entrire CURL slist.
procedure Curl_Slist_Free_All (List : in CURL_Slist_Access);
pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all");
-- Start a libcurl easy session.
function Curl_Easy_Init return CURL;
pragma Import (C, Curl_Easy_Init, "curl_easy_init");
-- End a libcurl easy session.
procedure Curl_Easy_Cleanup (Handle : in CURL);
pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup");
-- Perform a file transfer.
function Curl_Easy_Perform (Handle : in CURL) return CURL_Code;
pragma Import (C, Curl_Easy_Perform, "curl_easy_perform");
-- Return the error message which correspond to the given CURL error code.
function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr;
pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_String (Handle : in CURL;
Option : in Curl_Option;
Value : in Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Slist (Handle : in CURL;
Option : in Curl_Option;
Value : in CURL_Slist_Access) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Long (Handle : in CURL;
Option : in Curl_Option;
Value : in Interfaces.C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt");
-- Get information from a CURL handle for an option returning a String.
function Curl_Easy_Getinfo_String (Handle : in CURL;
Option : in CURL_Info;
Value : access Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo");
-- Get information from a CURL handle for an option returning a Long.
function Curl_Easy_Getinfo_Long (Handle : in CURL;
Option : in CURL_Info;
Value : access C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo");
type Write_Callback_Access is access
function (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Ptr : in Curl_Http_Response_Access) return Size_T;
pragma Convention (C, Write_Callback_Access);
function Curl_Easy_Setopt_Write_Callback
(Handle : in CURL;
Option : in Curl_Option;
Func : in Write_Callback_Access)
return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Data (Handle : in CURL;
Option : in Curl_Option;
Value : in Curl_Http_Response_Access) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt");
function Read_Response (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Response : in Curl_Http_Response_Access) return Size_T;
pragma Convention (C, Read_Response);
end Util.Http.Clients.Curl;
|
-----------------------------------------------------------------------
-- util-http-clients-curl -- HTTP Clients with CURL
-- Copyright (C) 2012, 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.Strings.Unbounded;
with Util.Http.Mockups;
package Util.Http.Clients.Curl is
-- Register the CURL Http manager.
procedure Register;
private
package C renames Interfaces.C;
package Strings renames Interfaces.C.Strings;
use type C.size_t;
-- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due
-- to Eclipse capitalization.
subtype Int is C.int;
subtype Chars_Ptr is Strings.chars_ptr;
subtype Size_T is C.size_t;
subtype CURL is System.Address;
type CURL_Code is new Interfaces.C.int;
CURLE_OK : constant CURL_Code := 0;
type CURL_Info is new Int;
type Curl_Option is new Int;
type CURL_Slist;
type CURL_Slist_Access is access CURL_Slist;
type CURL_Slist is record
Data : Chars_Ptr;
Next : CURL_Slist_Access;
end record;
-- Check the CURL result code and report and exception and a log message if
-- the CURL code indicates an error.
procedure Check_Code (Code : in CURL_Code;
Message : in String);
type Curl_Http_Manager is new Http_Manager with null record;
type Curl_Http_Manager_Access is access all Http_Manager'Class;
-- Create a new HTTP request associated with the current request manager.
procedure Create (Manager : in Curl_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Delete (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in Curl_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record
Data : CURL := System.Null_Address;
URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Curl_Headers : CURL_Slist_Access := null;
end record;
type Curl_Http_Request_Access is access all Curl_Http_Request'Class;
-- Prepare to setup the headers in the request.
procedure Set_Headers (Request : in out Curl_Http_Request);
overriding
procedure Finalize (Request : in out Curl_Http_Request);
type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record
C : CURL;
Content : Ada.Strings.Unbounded.Unbounded_String;
Status : Natural;
Parsing_Body : Boolean := False;
end record;
type Curl_Http_Response_Access is access all Curl_Http_Response'Class;
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Curl_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Curl_Http_Response) return Natural;
-- Add a string to a CURL slist.
function Curl_Slist_Append (List : in CURL_Slist_Access;
Value : in Chars_Ptr) return CURL_Slist_Access;
pragma Import (C, Curl_Slist_Append, "curl_slist_append");
-- Free an entrire CURL slist.
procedure Curl_Slist_Free_All (List : in CURL_Slist_Access);
pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all");
-- Start a libcurl easy session.
function Curl_Easy_Init return CURL;
pragma Import (C, Curl_Easy_Init, "curl_easy_init");
-- End a libcurl easy session.
procedure Curl_Easy_Cleanup (Handle : in CURL);
pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup");
-- Perform a file transfer.
function Curl_Easy_Perform (Handle : in CURL) return CURL_Code;
pragma Import (C, Curl_Easy_Perform, "curl_easy_perform");
-- Return the error message which correspond to the given CURL error code.
function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr;
pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_String (Handle : in CURL;
Option : in Curl_Option;
Value : in Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Slist (Handle : in CURL;
Option : in Curl_Option;
Value : in CURL_Slist_Access) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Long (Handle : in CURL;
Option : in Curl_Option;
Value : in Interfaces.C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt");
-- Get information from a CURL handle for an option returning a String.
function Curl_Easy_Getinfo_String (Handle : in CURL;
Option : in CURL_Info;
Value : access Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo");
-- Get information from a CURL handle for an option returning a Long.
function Curl_Easy_Getinfo_Long (Handle : in CURL;
Option : in CURL_Info;
Value : access C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo");
type Write_Callback_Access is access
function (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Ptr : in Curl_Http_Response_Access) return Size_T;
pragma Convention (C, Write_Callback_Access);
function Curl_Easy_Setopt_Write_Callback
(Handle : in CURL;
Option : in Curl_Option;
Func : in Write_Callback_Access)
return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Data (Handle : in CURL;
Option : in Curl_Option;
Value : in Curl_Http_Response_Access) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt");
function Read_Response (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Response : in Curl_Http_Response_Access) return Size_T;
pragma Convention (C, Read_Response);
end Util.Http.Clients.Curl;
|
Remove unecessary use type clause
|
Remove unecessary use type clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a6d2a77380680d1db7356887438ad71f5d887546
|
src/security-permissions.adb
|
src/security-permissions.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- 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.Unchecked_Deallocation;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Contexts;
with Security.Controllers;
with Security.Controllers.Roles;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
package body Permission_ACL is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Permission_ACL;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- 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.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
package body Permission_ACL is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Permission_ACL;
end Security.Permissions;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
3daaa0e0fbdfabf90fe3bcb50e48907d9313c45e
|
src/wiki-streams-text_io.adb
|
src/wiki-streams-text_io.adb
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
end Open;
-- ------------------------------
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is
Available : Boolean;
begin
Eof := False;
Ada.Wide_Wide_Text_IO.Get_immediate (Input.File, Char, Available);
exception
when Ada.IO_Exceptions.End_Error =>
Char := Wiki.Helpers.LF;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Create;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
end Write;
end Wiki.Streams.Text_IO;
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end Close;
-- ------------------------------
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is
Available : Boolean;
begin
Eof := False;
Ada.Wide_Wide_Text_IO.Get_immediate (Input.File, Char, Available);
exception
when Ada.IO_Exceptions.End_Error =>
Char := Wiki.Helpers.LF;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Create;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
end Write;
end Wiki.Streams.Text_IO;
|
Implement the Close procedure to close the opened file
|
Implement the Close procedure to close the opened file
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f3e5d634e2efb587965822c6256851b578bd1f51
|
src/security-auth-openid.ads
|
src/security-auth-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 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.
-----------------------------------------------------------------------
-- === OpenID Configuration ==
-- The Open ID provider needs the following configuration parameters:
--
-- openid.realm The OpenID realm parameter passed in the authentication URL.
-- openid.callback_url The OpenID return_to parameter.
--
private package Security.Auth.OpenID is
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is new Security.Auth.Manager with private;
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the 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);
-- 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
type Manager is new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
end record;
end Security.Auth.OpenID;
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 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.
-----------------------------------------------------------------------
-- === OpenID Configuration ==
-- The Open ID provider needs the following configuration parameters:
--
-- openid.realm The OpenID realm parameter passed in the authentication URL.
-- openid.callback_url The OpenID return_to parameter.
--
private package Security.Auth.OpenID is
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is new Security.Auth.Manager with private;
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the 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);
-- 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
type Manager is new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
end record;
end Security.Auth.OpenID;
|
Rename Initialize parameter
|
Rename Initialize parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
185c1d2ac5549c6aa5057e4e1599885c369c5568
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-modules-tests -- Unit tests for storage service
-- Copyright (C) 2012, 2013, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Images.Modules;
package body AWA.Images.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Images.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Create_Image",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Get_Sizes",
Test_Get_Sizes'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Scale",
Test_Scale'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg");
Thumb : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg");
Width : Natural := 64;
Height : Natural := 64;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Images.Modules.Get_Image_Module;
T.Manager.Create_Thumbnail (Source, Thumb, Width, Height);
Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width");
Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height");
end Test_Create_Image;
-- ------------------------------
-- Test the Get_Sizes operation.
-- ------------------------------
procedure Test_Get_Sizes (T : in out Test) is
Width : Natural;
Height : Natural;
begin
AWA.Images.Modules.Get_Sizes ("default", Width, Height);
Util.Tests.Assert_Equals (T, 800, Width, "Default width should be 800");
Util.Tests.Assert_Equals (T, 0, Height, "Default height should be 0");
AWA.Images.Modules.Get_Sizes ("123x456", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("x56", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 56, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123x", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("original", Width, Height);
Util.Tests.Assert_Equals (T, Natural'Last, Width, "Invalid width");
Util.Tests.Assert_Equals (T, Natural'Last, Height, "Invalid height");
end Test_Get_Sizes;
-- ------------------------------
-- Test the Scale operation.
-- ------------------------------
procedure Test_Scale (T : in out Test) is
Width : Natural;
Height : Natural;
begin
Width := 0;
Height := 0;
AWA.Images.Modules.Scale (123, 456, Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
Width := 100;
Height := 0;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 100, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 20, Height, "Invalid height");
Width := 0;
Height := 200;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 1000, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 200, Height, "Invalid height");
end Test_Scale;
end AWA.Images.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-modules-tests -- Unit tests for storage service
-- Copyright (C) 2012, 2013, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Images.Modules;
package body AWA.Images.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Images.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Create_Image",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Get_Sizes",
Test_Get_Sizes'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Scale",
Test_Scale'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg");
Thumb : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg");
Width : Natural := 64;
Height : Natural := 64;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Images.Modules.Get_Image_Module;
T.Manager.Create_Thumbnail (Source, Thumb, Width, Height);
Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width");
Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height");
end Test_Create_Image;
-- ------------------------------
-- Test the Get_Sizes operation.
-- ------------------------------
procedure Test_Get_Sizes (T : in out Test) is
Width : Natural;
Height : Natural;
begin
AWA.Images.Modules.Get_Sizes ("default", Width, Height);
Util.Tests.Assert_Equals (T, 800, Width, "Default width should be 800");
Util.Tests.Assert_Equals (T, 0, Height, "Default height should be 0");
AWA.Images.Modules.Get_Sizes ("123x456", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("x56", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 56, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123x", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("original", Width, Height);
Util.Tests.Assert_Equals (T, Natural'Last, Width, "Invalid width");
Util.Tests.Assert_Equals (T, Natural'Last, Height, "Invalid height");
end Test_Get_Sizes;
-- ------------------------------
-- Test the Scale operation.
-- ------------------------------
procedure Test_Scale (T : in out Test) is
Width : Natural;
Height : Natural;
begin
Width := 0;
Height := 0;
AWA.Images.Modules.Scale (123, 456, Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
Width := 100;
Height := 0;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 100, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 20, Height, "Invalid height");
Width := 0;
Height := 200;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 1000, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 200, Height, "Invalid height");
end Test_Scale;
end AWA.Images.Modules.Tests;
|
Fix the test for Get_Sizes
|
Fix the test for Get_Sizes
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a3e63a8889f89ef97c3d5e080541f91fae131fc4
|
src/util-encoders-base16.adb
|
src/util-encoders-base16.adb
|
-----------------------------------------------------------------------
-- util-encoders-base16 -- Encode/Decode a stream in hexadecimal
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Encoders.Base16 is
package body Encoding is
type Code is mod 2**32;
function To_Output_Char (Ch : Input_Char) return Code;
type Conv_Table is array (0 .. 15) of Output_Char;
Conversion : constant Conv_Table :=
(0 => Output_Char'Val (Character'Pos ('0')),
1 => Output_Char'Val (Character'Pos ('1')),
2 => Output_Char'Val (Character'Pos ('2')),
3 => Output_Char'Val (Character'Pos ('3')),
4 => Output_Char'Val (Character'Pos ('4')),
5 => Output_Char'Val (Character'Pos ('5')),
6 => Output_Char'Val (Character'Pos ('6')),
7 => Output_Char'Val (Character'Pos ('7')),
8 => Output_Char'Val (Character'Pos ('8')),
9 => Output_Char'Val (Character'Pos ('9')),
10 => Output_Char'Val (Character'Pos ('A')),
11 => Output_Char'Val (Character'Pos ('B')),
12 => Output_Char'Val (Character'Pos ('C')),
13 => Output_Char'Val (Character'Pos ('D')),
14 => Output_Char'Val (Character'Pos ('E')),
15 => Output_Char'Val (Character'Pos ('F')));
-- Encode the input stream in hexadecimal and write the result
-- in the output stream
procedure Encode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index) is
N : constant Output_Index := (Input_Char'Size / 8) * 2;
Pos : Output_Index := Into'First;
begin
for I in From'Range loop
if Pos + N > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
declare
Value : Code := Input_Char'Pos (From (I));
P : Code;
begin
Pos := Pos + N;
for J in 1 .. N / 2 loop
P := Value;
Value := Value / 16;
Into (Pos - J) := Conversion (Natural (P and 16#0F#));
P := Value;
Into (Pos - J - 1) := Conversion (Natural (P and 16#0F#));
Value := Value / 16;
end loop;
end;
end loop;
Last := Pos - 1;
Encoded := From'Last;
end Encode;
function To_Output_Char (Ch : Input_Char) return Code is
C : constant Code := Input_Char'Pos (Ch);
begin
if C >= Character'Pos ('a') and C <= Character'Pos ('f') then
return C - Character'Pos ('a') + 10;
elsif C >= Character'Pos ('A') and C <= Character'Pos ('F') then
return C - Character'Pos ('A') + 10;
elsif C >= Character'Pos ('0') and C <= Character'Pos ('9') then
return C - Character'Pos ('0');
else
raise Encoding_Error with "Invalid character: " & Character'Val (C);
end if;
end To_Output_Char;
procedure Decode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index) is
First : Boolean := True;
Pos : Output_Index := Into'First;
Value : Code;
begin
if Into'Length < From'Length / 2 then
Encoded := Into'Length * 2;
elsif From'Last mod 2 /= 0 then
Encoded := From'Last - 1;
else
Encoded := From'Last;
end if;
if Encoded < From'First then
raise Encoding_Error with "Hexadecimal stream is too short";
end if;
for I in From'First .. Encoded loop
if First then
Value := To_Output_Char (From (I));
First := False;
else
Value := Value * 16 + To_Output_Char (From (I));
Into (Pos) := Output_Char'Val (Value);
Pos := Pos + 1;
First := True;
end if;
end loop;
Last := Pos - 1;
end Decode;
end Encoding;
package Encoding_Stream is new Encoding (Output => Ada.Streams.Stream_Element_Array,
Index => Ada.Streams.Stream_Element_Offset,
Output_Index => Ada.Streams.Stream_Element_Offset,
Input_Char => Ada.Streams.Stream_Element,
Output_Char => Ada.Streams.Stream_Element,
Input => Ada.Streams.Stream_Element_Array);
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base16 (hexadecimal) output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
pragma Unreferenced (E);
begin
Encoding_Stream.Encode (Data, Into, Last, Encoded);
end Transform;
-- ------------------------------
-- Decodes the base16 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
pragma Unreferenced (E);
begin
Encoding_Stream.Decode (Data, Into, Last, Encoded);
end Transform;
end Util.Encoders.Base16;
|
-----------------------------------------------------------------------
-- util-encoders-base16 -- Encode/Decode a stream in hexadecimal
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
package body Util.Encoders.Base16 is
package body Encoding is
type Code is mod 2**32;
function To_Output_Char (Ch : Input_Char) return Code;
type Conv_Table is array (0 .. 15) of Output_Char;
Conversion : constant Conv_Table :=
(0 => Output_Char'Val (Character'Pos ('0')),
1 => Output_Char'Val (Character'Pos ('1')),
2 => Output_Char'Val (Character'Pos ('2')),
3 => Output_Char'Val (Character'Pos ('3')),
4 => Output_Char'Val (Character'Pos ('4')),
5 => Output_Char'Val (Character'Pos ('5')),
6 => Output_Char'Val (Character'Pos ('6')),
7 => Output_Char'Val (Character'Pos ('7')),
8 => Output_Char'Val (Character'Pos ('8')),
9 => Output_Char'Val (Character'Pos ('9')),
10 => Output_Char'Val (Character'Pos ('A')),
11 => Output_Char'Val (Character'Pos ('B')),
12 => Output_Char'Val (Character'Pos ('C')),
13 => Output_Char'Val (Character'Pos ('D')),
14 => Output_Char'Val (Character'Pos ('E')),
15 => Output_Char'Val (Character'Pos ('F')));
-- Encode the input stream in hexadecimal and write the result
-- in the output stream
procedure Encode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index) is
N : constant Output_Index := (Input_Char'Size / 8) * 2;
Pos : Output_Index := Into'First;
begin
for I in From'Range loop
if Pos + N > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
declare
Value : Code := Input_Char'Pos (From (I));
P : Code;
begin
Pos := Pos + N;
for J in 1 .. N / 2 loop
P := Value;
Value := Value / 16;
Into (Pos - J) := Conversion (Natural (P and 16#0F#));
P := Value;
Into (Pos - J - 1) := Conversion (Natural (P and 16#0F#));
Value := Value / 16;
end loop;
end;
end loop;
Last := Pos - 1;
Encoded := From'Last;
end Encode;
function To_Output_Char (Ch : Input_Char) return Code is
C : constant Code := Input_Char'Pos (Ch);
begin
if C >= Character'Pos ('a') and C <= Character'Pos ('f') then
return C - Character'Pos ('a') + 10;
elsif C >= Character'Pos ('A') and C <= Character'Pos ('F') then
return C - Character'Pos ('A') + 10;
elsif C >= Character'Pos ('0') and C <= Character'Pos ('9') then
return C - Character'Pos ('0');
else
raise Encoding_Error with "Invalid character: " & Character'Val (C);
end if;
end To_Output_Char;
procedure Decode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index) is
First : Boolean := True;
Pos : Output_Index := Into'First;
Value : Code;
begin
if Into'Length < From'Length / 2 then
Encoded := Into'Length * 2;
elsif From'Last mod 2 /= 0 then
Encoded := From'Last - 1;
else
Encoded := From'Last;
end if;
if Encoded < From'First then
raise Encoding_Error with "Hexadecimal stream is too short";
end if;
for I in From'First .. Encoded loop
if First then
Value := To_Output_Char (From (I));
First := False;
else
Value := Value * 16 + To_Output_Char (From (I));
Into (Pos) := Output_Char'Val (Value);
Pos := Pos + 1;
First := True;
end if;
end loop;
Last := Pos - 1;
end Decode;
end Encoding;
package Encoding_Stream is new Encoding (Output => Ada.Streams.Stream_Element_Array,
Index => Ada.Streams.Stream_Element_Offset,
Output_Index => Ada.Streams.Stream_Element_Offset,
Input_Char => Ada.Streams.Stream_Element,
Output_Char => Ada.Streams.Stream_Element,
Input => Ada.Streams.Stream_Element_Array);
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base16 (hexadecimal) output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
pragma Unreferenced (E);
begin
Encoding_Stream.Encode (Data, Into, Last, Encoded);
end Transform;
-- ------------------------------
-- Decodes the base16 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in out Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
pragma Unreferenced (E);
begin
Encoding_Stream.Decode (Data, Into, Last, Encoded);
end Transform;
end Util.Encoders.Base16;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
50d592d888f09f542f336d0995711efe43221f6d
|
mat/src/mat-readers-marshaller.adb
|
mat/src/mat-readers-marshaller.adb
|
-----------------------------------------------------------------------
-- Ipc -- Ipc channel between profiler tool and application --
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System; use System;
with System.Address_To_Access_Conversions;
with System.Storage_Elements;
with Util.Log.Loggers;
with Interfaces; use Interfaces;
package body MAT.Readers.Marshaller is
use System.Storage_Elements;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller");
package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8);
package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32);
function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is
use Uint32_Access;
P : constant Object_Pointer := To_Pointer (Buf);
begin
return P.all;
end Get_Raw_Uint32;
function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is
use Uint8_Access;
P : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size = 0 then
Log.Error ("Not enough data to get a uint8");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 1;
Buffer.Current := Buffer.Current + Storage_Offset (1);
return P.all;
end Get_Uint8;
function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is
use Uint8_Access;
High : constant Object_Pointer := To_Pointer (Buffer.Current
+ Storage_Offset (1));
Low : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size <= 1 then
Log.Error ("Not enough data to get a uint16");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 2;
Buffer.Current := Buffer.Current + Storage_Offset (2);
return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all);
end Get_Uint16;
function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is
use Uint32_Access;
P : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size < 4 then
Log.Error ("Not enough data to get a uint32");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 4;
Buffer.Current := Buffer.Current + Storage_Offset (4);
if Buffer.Current >= Buffer.Last then
Buffer.Current := Buffer.Start;
end if;
return P.all;
end Get_Uint32;
function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is
Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer));
begin
return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32;
end Get_Uint64;
function Get_Target_Value (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return Target_Type is
begin
case Kind is
when MAT.Events.T_UINT8 =>
return Target_Type (Get_Uint8 (Msg));
when MAT.Events.T_UINT16 =>
return Target_Type (Get_Uint16 (Msg));
when MAT.Events.T_UINT32 =>
return Target_Type (Get_Uint32 (Msg));
when MAT.Events.T_UINT64 =>
return Target_Type (Get_Uint64 (Msg));
when others =>
Log.Error ("Invalid attribute type {0}",
MAT.Events.Attribute_Type'Image (Kind));
return 0;
end case;
end Get_Target_Value;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Buffer : in Buffer_Ptr) return String is
Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer);
Result : String (1 .. Natural (Len));
begin
for I in Result'Range loop
Result (I) := Character'Val (Get_Uint8 (Buffer));
end loop;
return Result;
end Get_String;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg));
end Get_String;
-- ------------------------------
-- Skip the given number of bytes from the message.
-- ------------------------------
procedure Skip (Buffer : in Buffer_Ptr;
Size : in Natural) is
begin
Buffer.Size := Buffer.Size - Size;
Buffer.Current := Buffer.Current + Storage_Offset (Size);
end Skip;
function Get_Target_Size (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Size);
begin
return Get_Value (Msg, Kind);
end Get_Target_Size;
function Get_Target_Addr (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Addr;
function Get_Target_Uint32 (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Uint32;
end MAT.Readers.Marshaller;
|
-----------------------------------------------------------------------
-- Ipc -- Ipc channel between profiler tool and application --
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with System; use System;
with System.Address_To_Access_Conversions;
with System.Storage_Elements;
with Util.Log.Loggers;
with Interfaces; use Interfaces;
package body MAT.Readers.Marshaller is
use System.Storage_Elements;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller");
package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8);
package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32);
function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is
use Uint32_Access;
P : constant Object_Pointer := To_Pointer (Buf);
begin
return P.all;
end Get_Raw_Uint32;
-- ------------------------------
-- Get an 8-bit value from the buffer.
-- ------------------------------
function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is
use Uint8_Access;
P : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size = 0 then
Log.Error ("Not enough data to get a uint8");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 1;
Buffer.Current := Buffer.Current + Storage_Offset (1);
return P.all;
end Get_Uint8;
function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is
use Uint8_Access;
High : Object_Pointer;
Low : Object_Pointer;
begin
if Buffer.Size <= 1 then
Log.Error ("Not enough data to get a uint16");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := To_Pointer (Buffer.Current);
High := To_Pointer (Buffer.Current + Storage_Offset (1));
else
High := To_Pointer (Buffer.Current);
Low := To_Pointer (Buffer.Current + Storage_Offset (1));
end if;
Buffer.Size := Buffer.Size - 2;
Buffer.Current := Buffer.Current + Storage_Offset (2);
return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all);
end Get_Uint16;
function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is
use Uint32_Access;
Low, High : MAT.Types.Uint16;
begin
if Buffer.Size < 4 then
Log.Error ("Not enough data to get a uint32");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := Get_Uint16 (Buffer);
High := Get_Uint16 (Buffer);
else
High := Get_Uint16 (Buffer);
Low := Get_Uint16 (Buffer);
end if;
return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low);
end Get_Uint32;
function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is
Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer));
begin
return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32;
end Get_Uint64;
function Get_Target_Value (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return Target_Type is
begin
case Kind is
when MAT.Events.T_UINT8 =>
return Target_Type (Get_Uint8 (Msg));
when MAT.Events.T_UINT16 =>
return Target_Type (Get_Uint16 (Msg));
when MAT.Events.T_UINT32 =>
return Target_Type (Get_Uint32 (Msg));
when MAT.Events.T_UINT64 =>
return Target_Type (Get_Uint64 (Msg));
when others =>
Log.Error ("Invalid attribute type {0}",
MAT.Events.Attribute_Type'Image (Kind));
return 0;
end case;
end Get_Target_Value;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Buffer : in Buffer_Ptr) return String is
Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer);
Result : String (1 .. Natural (Len));
begin
for I in Result'Range loop
Result (I) := Character'Val (Get_Uint8 (Buffer));
end loop;
return Result;
end Get_String;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg));
end Get_String;
-- ------------------------------
-- Skip the given number of bytes from the message.
-- ------------------------------
procedure Skip (Buffer : in Buffer_Ptr;
Size : in Natural) is
begin
Buffer.Size := Buffer.Size - Size;
Buffer.Current := Buffer.Current + Storage_Offset (Size);
end Skip;
function Get_Target_Size (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Size);
begin
return Get_Value (Msg, Kind);
end Get_Target_Size;
function Get_Target_Addr (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Addr;
function Get_Target_Uint32 (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Uint32;
end MAT.Readers.Marshaller;
|
Document Get_Uint8 and fix Get_Uint16 to support big/little endian
|
Document Get_Uint8 and fix Get_Uint16 to support big/little endian
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c7eac29bc45d50ac27334c4b70c55defb3524af2
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Votes.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Votes.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For",
Test_Vote_Up'Access);
Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For (Undo)",
Test_Vote_Undo'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Vote_Up (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
Vote_Manager : constant Vote_Module_Access := Get_Vote_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
Total : Integer;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total);
T.Assert (Total > 0, "Invalid total");
end;
end Test_Vote_Up;
-- ------------------------------
-- Test vote.
-- ------------------------------
procedure Test_Vote_Undo (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
Vote_Manager : constant Vote_Module_Access := Get_Vote_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
Total : Integer;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 0, Total);
T.Assert (Total >= 0, "Invalid total");
end;
end Test_Vote_Undo;
end AWA.Votes.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013, 2018, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
package body AWA.Votes.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For",
Test_Vote_Up'Access);
Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For (Undo)",
Test_Vote_Undo'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Vote_Up (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
Vote_Manager : constant Vote_Module_Access := Get_Vote_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
Total : Integer;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total);
T.Assert (Total > 0, "Invalid total");
end;
end Test_Vote_Up;
-- ------------------------------
-- Test vote.
-- ------------------------------
procedure Test_Vote_Undo (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
Vote_Manager : constant Vote_Module_Access := Get_Vote_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
Total : Integer;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total);
T.Assert (Total > 0, "Invalid total");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 0, Total);
T.Assert (Total >= 0, "Invalid total");
end;
end Test_Vote_Undo;
end AWA.Votes.Modules.Tests;
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2bfa894e1064ac255aca6050601ee8e767e58bc1
|
mat/src/mat-consoles.ads
|
mat/src/mat-consoles.ads
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_ID,
F_OLD_ADDR,
F_TIME,
F_EVENT,
F_FRAME_ID,
F_FRAME_ADDR);
type Notice_Type is (N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_ID,
F_OLD_ADDR,
F_TIME,
F_EVENT,
F_FRAME_ID,
F_FRAME_ADDR);
type Notice_Type is (N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Add a Justify parameter to the Print_Field procedure
|
Add a Justify parameter to the Print_Field procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b762fc6de893c1c30663cf38bc91e4ac199ad6b4
|
awa/plugins/awa-questions/src/awa-questions-modules.adb
|
awa/plugins/awa-questions/src/awa-questions-modules.adb
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Characters.Conversions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with Wiki.Parsers;
with Wiki.Utils;
with ADO.Sessions;
with ADO.Statements;
with Util.Log.Loggers;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Questions.Beans;
with AWA.Applications;
package body AWA.Questions.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module");
package Register is new AWA.Modules.Beans (Module => Question_Module,
Module_Access => Question_Module_Access);
-- ------------------------------
-- Initialize the questions module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the questions module");
-- Setup the resource bundles.
App.Register ("questionMsg", "questions");
-- Edit and save a question.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
-- Edit and save an answer.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Answer_Bean",
Handler => AWA.Questions.Beans.Create_Answer_Bean'Access);
-- List of questions.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_List_Bean",
Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access);
-- Display a question with its answers.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Display_Bean",
Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the questions module.
-- ------------------------------
function Get_Question_Module return Question_Module_Access is
function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME);
begin
return Get;
end Get_Question_Module;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Ctx.Start;
if Question.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id));
WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace);
else
Log.Info ("Creating new question {0}", String '(Question.Get_Title));
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission,
Entity => WS);
Question.Set_Workspace (WS);
Question.Set_Author (User);
end if;
declare
Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description),
Wiki.Parsers.SYNTAX_MIX);
Last : Natural;
begin
if Text'Length < SHORT_DESCRIPTION_LENGTH then
Last := Text'Last;
else
Last := SHORT_DESCRIPTION_LENGTH;
end if;
Question.Set_Short_Description (Text (Text'First .. Last) & "...");
end;
if not Question.Is_Inserted then
Question.Set_Create_Date (Ada.Calendar.Clock);
else
Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Question.Save (DB);
Ctx.Commit;
end Save_Question;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given question.
AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission,
Entity => Question);
-- Before deleting the question, delete the associated answers.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE);
begin
Stmt.Set_Filter (Filter => "question_id = ?");
Stmt.Add_Param (Value => Question);
Stmt.Execute;
end;
Question.Delete (DB);
Ctx.Commit;
end Delete_Question;
-- ------------------------------
-- Load the question.
-- ------------------------------
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Question.Load (DB, Id, Found);
end Load_Question;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
if Answer.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id));
else
Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission,
Entity => Question);
Answer.Set_Author (User);
end if;
if not Answer.Is_Inserted then
Answer.Set_Create_Date (Ada.Calendar.Clock);
Answer.Set_Question (Question);
else
Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock,
Is_Null => False));
end if;
Answer.Save (DB);
Ctx.Commit;
end Save_Answer;
-- ------------------------------
-- Delete the answer.
-- ------------------------------
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission,
Entity => Answer);
Answer.Delete (DB);
Ctx.Commit;
end Delete_Answer;
-- ------------------------------
-- Load the answer.
-- ------------------------------
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Answer.Load (DB, Id, Found);
Question := Answer.Get_Question;
end Load_Answer;
end AWA.Questions.Modules;
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Characters.Conversions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with Wiki;
with Wiki.Utils;
with ADO.Sessions;
with ADO.Statements;
with Util.Log.Loggers;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Questions.Beans;
with AWA.Applications;
package body AWA.Questions.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module");
package Register is new AWA.Modules.Beans (Module => Question_Module,
Module_Access => Question_Module_Access);
-- ------------------------------
-- Initialize the questions module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the questions module");
-- Setup the resource bundles.
App.Register ("questionMsg", "questions");
-- Edit and save a question.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Bean",
Handler => AWA.Questions.Beans.Create_Question_Bean'Access);
-- Edit and save an answer.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Answer_Bean",
Handler => AWA.Questions.Beans.Create_Answer_Bean'Access);
-- List of questions.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_List_Bean",
Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access);
-- Display a question with its answers.
Register.Register (Plugin => Plugin,
Name => "AWA.Questions.Beans.Question_Display_Bean",
Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the questions module.
-- ------------------------------
function Get_Question_Module return Question_Module_Access is
function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME);
begin
return Get;
end Get_Question_Module;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Ctx.Start;
if Question.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id));
WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace);
else
Log.Info ("Creating new question {0}", String '(Question.Get_Title));
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission,
Entity => WS);
Question.Set_Workspace (WS);
Question.Set_Author (User);
end if;
declare
Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description),
Wiki.SYNTAX_MIX);
Last : Natural;
begin
if Text'Length < SHORT_DESCRIPTION_LENGTH then
Last := Text'Last;
else
Last := SHORT_DESCRIPTION_LENGTH;
end if;
Question.Set_Short_Description (Text (Text'First .. Last) & "...");
end;
if not Question.Is_Inserted then
Question.Set_Create_Date (Ada.Calendar.Clock);
else
Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Question.Save (DB);
Ctx.Commit;
end Save_Question;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given question.
AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission,
Entity => Question);
-- Before deleting the question, delete the associated answers.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE);
begin
Stmt.Set_Filter (Filter => "question_id = ?");
Stmt.Add_Param (Value => Question);
Stmt.Execute;
end;
Question.Delete (DB);
Ctx.Commit;
end Delete_Question;
-- ------------------------------
-- Load the question.
-- ------------------------------
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Question.Load (DB, Id, Found);
end Load_Question;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
if Answer.Is_Inserted then
Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id));
else
Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission,
Entity => Question);
Answer.Set_Author (User);
end if;
if not Answer.Is_Inserted then
Answer.Set_Create_Date (Ada.Calendar.Clock);
Answer.Set_Question (Question);
else
Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock,
Is_Null => False));
end if;
Answer.Save (DB);
Ctx.Commit;
end Save_Answer;
-- ------------------------------
-- Delete the answer.
-- ------------------------------
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission,
Entity => Answer);
Answer.Delete (DB);
Ctx.Commit;
end Delete_Answer;
-- ------------------------------
-- Load the answer.
-- ------------------------------
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Answer.Load (DB, Id, Found);
Question := Answer.Get_Question;
end Load_Answer;
end AWA.Questions.Modules;
|
Fix to use the Wiki.SYNTAX_MIX after Ada Wiki refactoring
|
Fix to use the Wiki.SYNTAX_MIX after Ada Wiki refactoring
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a45ab0b74aaa8035003fc8551d4b19ba6acacf72
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Send the invitation
|
Send the invitation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1a09b01c589060fa138a451b7dd26d0f78bf4c46
|
awa/plugins/awa-storages/src/awa-storages.ads
|
awa/plugins/awa-storages/src/awa-storages.ads
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area.
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Data Model ==
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Web Services.
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png]
--
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
Document the storage plugin
|
Document the storage plugin
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
581a96a7c22b504eb914ede4bf86ffc7761c1fce
|
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;
with AWA.Storages.Stores.Files;
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 store identified by <tt>Kind</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
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
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);
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 instance identified by the given identifier.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) 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);
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;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
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;
Created := not Into.Is_Inserted;
if Created 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);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
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;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
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 Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) 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;
Local : AWA.Storages.Models.Store_Local_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);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
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);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_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);
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_Lifecycle.Notify_Delete (Service, Storage);
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.Get_Storage);
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;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE'Access);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- 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;
with AWA.Storages.Stores.Files;
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 store identified by <tt>Kind</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
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
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);
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);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder instance identified by the given identifier.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) 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);
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;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
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;
Created := not Into.Is_Inserted;
if Created 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);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
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;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
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 Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) 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;
Local : AWA.Storages.Models.Store_Local_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);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
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);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_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);
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_Lifecycle.Notify_Delete (Service, Storage);
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.Get_Storage);
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;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE'Access);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- 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 folder owner when creating it
|
Set the folder owner when creating it
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
09571394948d0bfbccc0c5e485b2e210be429924
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
with Wiki.Strings;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Wiki_Module;
Props : in ASF.Applications.Config);
-- Get the image prefix that was configured for the Wiki module.
function Get_Image_Prefix (Module : in Wiki_Module)
return Wiki.Strings.UString;
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
end record;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Wikis.Servlets;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
with Wiki.Strings;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Wiki_Module;
Props : in ASF.Applications.Config);
-- Get the image prefix that was configured for the Wiki module.
function Get_Image_Prefix (Module : in Wiki_Module)
return Wiki.Strings.UString;
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
procedure Load_Image (Model : in Wiki_Module;
Wiki_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Wikis.Servlets.Image_Servlet;
end record;
end AWA.Wikis.Modules;
|
Declare Load_Image procedure Add the image servlet to render wiki images
|
Declare Load_Image procedure
Add the image servlet to render wiki images
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
39235ac046028de5855df0facae3261fb585856f
|
src/ado-sessions-factory.ads
|
src/ado-sessions-factory.ads
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Databases;
with ADO.Schemas.Entities;
with ADO.Sequences;
with ADO.Caches;
-- === Session Factory ===
-- The session factory is the entry point to obtain a database session.
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the <tt>Create</tt> operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or
-- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
package ADO.Sessions.Factory is
pragma Elaborate_Body;
ENTITY_CACHE_NAME : constant String := "entity_type";
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record
Source : ADO.Databases.DataSource;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
-- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
Cache : aliased ADO.Caches.Cache_Manager;
Cache_Values : ADO.Caches.Cache_Manager_Access;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Schemas.Entities;
with ADO.Sequences;
with ADO.Caches;
with ADO.Sessions.Sources;
-- === Session Factory ===
-- The session factory is the entry point to obtain a database session.
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the <tt>Create</tt> operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or
-- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
package ADO.Sessions.Factory is
pragma Elaborate_Body;
ENTITY_CACHE_NAME : constant String := "entity_type";
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record
Source : ADO.Sessions.Sources.Data_Source;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
-- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
Cache : aliased ADO.Caches.Cache_Manager;
Cache_Values : ADO.Caches.Cache_Manager_Access;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Use the ADO.Sessions.Sources package for data source representation
|
Use the ADO.Sessions.Sources package for data source representation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
631781dd0c1cc8ce076abbc1b60647e637502446
|
src/asf-security-filters-oauth.adb
|
src/asf-security-filters-oauth.adb
|
-----------------------------------------------------------------------
-- security-filters-oauth -- OAuth Security filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters.OAuth is
use Ada.Strings.Unbounded;
use Servers;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters.OAuth");
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
use ASF.Applications;
Context : constant Servlets.Servlet_Registry_Access := Servlets.Get_Servlet_Context (Config);
begin
if Context.all in Main.Application'Class then
Server.Set_Permission_Manager (Main.Application'Class (Context.all).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- 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) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String is
Header : constant String := Request.Get_Header (AUTHORIZATION_HEADER_NAME);
begin
if Header'Length > 0 then
return Header;
end if;
return Header;
end Get_Access_Token;
-- ------------------------------
-- 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) is
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
begin
if F.Realm = null then
Log.Error ("Deny access on {0} due to missing realm", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
declare
Bearer : constant String := Get_Access_Token (Request);
Auth : Principal_Access;
Grant : Servers.Grant_Type;
Context : aliased Contexts.Security_Context;
begin
if Bearer'Length = 0 then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
if Grant.Status /= Valid_Grant then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
-- OAuth_Permission
-- if not F.Manager.Has_Permission (Context, Perm) then
-- -- deny
-- Request.Set_Attribute ("application", Grant.Application);
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end;
end Do_Filter;
-- ------------------------------
-- 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) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- 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) is
pragma Unreferenced (Request);
begin
Response.Add_Header (WWW_AUTHENTICATE_HEADER_NAME,
"Bearer realm=""" & To_String (F.Realm_URL)
& """, error=""invalid_token""");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
end ASF.Security.Filters.OAuth;
|
-----------------------------------------------------------------------
-- security-filters-oauth -- OAuth Security filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Applications.Main;
with Security.Policies.URLs;
package body ASF.Security.Filters.OAuth is
use Ada.Strings.Unbounded;
use Servers;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters.OAuth");
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
use ASF.Applications;
Context : constant Servlets.Servlet_Registry_Access := Servlets.Get_Servlet_Context (Config);
begin
if Context.all in Main.Application'Class then
Server.Set_Permission_Manager (Main.Application'Class (Context.all).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- 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) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String is
Header : constant String := Request.Get_Header (AUTHORIZATION_HEADER_NAME);
begin
if Header'Length > 0 then
return Header;
end if;
return Header;
end Get_Access_Token;
-- ------------------------------
-- 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) is
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
begin
if F.Realm = null then
Log.Error ("Deny access on {0} due to missing realm", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
declare
Bearer : constant String := Get_Access_Token (Request);
-- Auth : Principal_Access;
Grant : Servers.Grant_Type;
-- Context : aliased Contexts.Security_Context;
begin
if Bearer'Length = 0 then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
if Grant.Status /= Valid_Grant then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
-- OAuth_Permission
-- if not F.Manager.Has_Permission (Context, Perm) then
-- -- deny
-- Request.Set_Attribute ("application", Grant.Application);
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end;
end Do_Filter;
-- ------------------------------
-- 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) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- 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) is
pragma Unreferenced (Request);
begin
Response.Add_Header (WWW_AUTHENTICATE_HEADER_NAME,
"Bearer realm=""" & To_String (F.Realm_URL)
& """, error=""invalid_token""");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
end ASF.Security.Filters.OAuth;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
8c0d664548cd4c47b9f1abcb72a7f4c780b23e0c
|
src/orka/implementation/orka-resources-textures-ktx.adb
|
src/orka/implementation/orka-resources-textures-ktx.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Unchecked_Deallocation;
with GL.Low_Level.Enums;
with GL.Types;
with GL.Pixels.Queries;
with Orka.Logging;
with Orka.KTX;
package body Orka.Resources.Textures.KTX is
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Resource_Loader);
type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record
Data : Loaders.Resource_Data;
Manager : Managers.Manager_Ptr;
end record;
overriding
procedure Execute
(Object : KTX_Load_Job;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr));
-----------------------------------------------------------------------------
use all type Ada.Real_Time.Time;
overriding
procedure Execute
(Object : KTX_Load_Job;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr))
is
Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get;
Path : String renames SU.To_String (Object.Data.Path);
T1 : Ada.Real_Time.Time renames Object.Data.Start_Time;
T2 : constant Ada.Real_Time.Time := Clock;
use Ada.Streams;
use GL.Low_Level.Enums;
use type GL.Types.Size;
T3, T4, T5, T6 : Ada.Real_Time.Time;
begin
if not Orka.KTX.Valid_Identifier (Bytes) then
raise Texture_Load_Error with Path & " is not a KTX file";
end if;
declare
Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes);
Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels);
Resource : constant Texture_Ptr := new Texture'(others => <>);
Texture : GL.Objects.Textures.Texture (Header.Kind);
Width : constant GL.Types.Size := Header.Width;
Height : GL.Types.Size := Header.Height;
Depth : GL.Types.Size := Header.Depth;
begin
T3 := Clock;
-- Allocate storage
case Header.Kind is
when Texture_2D_Array =>
Depth := Header.Array_Elements;
when Texture_1D_Array =>
Height := Header.Array_Elements;
pragma Assert (Depth = 0);
when Texture_Cube_Map_Array =>
-- For a cube map array, depth is the number of layer-faces
Depth := Header.Array_Elements * 6;
when Texture_3D =>
null;
when Texture_2D | Texture_Cube_Map =>
pragma Assert (Depth = 0);
when Texture_1D =>
if Header.Compressed then
raise Texture_Load_Error with Path & " has unknown 1D compressed format";
end if;
pragma Assert (Height = 0);
pragma Assert (Depth = 0);
when others =>
raise Program_Error;
end case;
if Header.Compressed then
Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format,
Width, Height, Depth);
else
Texture.Allocate_Storage (Levels, 1, Header.Internal_Format,
Width, Height, Depth);
end if;
case Header.Kind is
when Texture_1D =>
Height := 1;
Depth := 1;
when Texture_1D_Array | Texture_2D =>
Depth := 1;
when Texture_2D_Array | Texture_3D =>
null;
when Texture_Cube_Map | Texture_Cube_Map_Array =>
-- Texture_Cube_Map uses 2D storage, but 3D load operation
-- according to table 8.15 of the OpenGL specification
-- For a cube map, depth is the number of faces, for
-- a cube map array, depth is the number of layer-faces
Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6;
when others =>
raise Program_Error;
end case;
T4 := Clock;
-- TODO Handle KTXorientation key value pair
-- Upload texture data
declare
Image_Size_Index : Stream_Element_Offset
:= Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value);
Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map;
begin
for Level in 0 .. Levels - 1 loop
declare
Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index);
-- If not Cube_Map, then Face_Size is the size of the whole level
Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4);
Image_Size : constant Natural
:= (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size);
-- If Cube_Map then Levels = 1 so no need to add it to the expression
-- Compute size of the whole mipmap level
Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4);
Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding;
Offset : constant Stream_Element_Offset := Image_Size_Index + 4;
pragma Assert
(Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last);
Image_Data : constant System.Address := Bytes (Offset)'Address;
-- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4
-- depending on Header.Data_Type
Level_Width : constant GL.Types.Size := Texture.Width (Level);
Level_Height : GL.Types.Size := Texture.Height (Level);
Level_Depth : GL.Types.Size := Texture.Depth (Level);
begin
if Header.Compressed then
Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth,
Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data);
else
Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth,
Header.Format, Header.Data_Type, Image_Data);
end if;
Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size);
end;
end loop;
end;
T5 := Clock;
-- Generate a full mipmap pyramid if Mipmap_Levels = 0
if Header.Mipmap_Levels = 0 then
Texture.Generate_Mipmap;
end if;
T6 := Clock;
Resource.Texture.Replace_Element (Texture);
-- Register resource at the resource manager
Object.Manager.Add_Resource (Path, Resource_Ptr (Resource));
Messages.Insert (Info, "Loaded texture " & Path & " in " &
Logging.Trim (Logging.Image (T6 - T1)));
Messages.Insert (Info, " size: " &
Logging.Trim (Width'Image) & " x " &
Logging.Trim (Height'Image) & " x " &
Logging.Trim (Depth'Image) &
", mipmap levels:" & Levels'Image);
Messages.Insert (Info, " kind: " & Header.Kind'Image);
if Header.Compressed then
Messages.Insert (Info, " format: " & Header.Compressed_Format'Image);
else
Messages.Insert (Info, " format: " & Header.Internal_Format'Image);
end if;
Messages.Insert (Info, " statistics:");
Messages.Insert (Info, " reading file: " & Logging.Image (T2 - T1));
Messages.Insert (Info, " parsing header: " & Logging.Image (T3 - T2));
Messages.Insert (Info, " storage: " & Logging.Image (T4 - T3));
Messages.Insert (Info, " buffers: " & Logging.Image (T5 - T4));
if Header.Mipmap_Levels = 0 then
Messages.Insert (Info, " generating mipmap:" & Logging.Image (T6 - T5));
end if;
end;
exception
when Error : Orka.KTX.Invalid_Enum_Error =>
declare
Message : constant String := Ada.Exceptions.Exception_Message (Error);
begin
raise Texture_Load_Error with Path & " has " & Message;
end;
end Execute;
-----------------------------------------------------------------------------
-- Loader --
-----------------------------------------------------------------------------
type KTX_Loader is limited new Loaders.Loader with record
Manager : Managers.Manager_Ptr;
end record;
overriding
function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx");
overriding
procedure Load
(Object : KTX_Loader;
Data : Loaders.Resource_Data;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr);
Location : Locations.Location_Ptr)
is
Job : constant Jobs.Job_Ptr := new KTX_Load_Job'
(Jobs.Abstract_Job with
Data => Data,
Manager => Object.Manager);
begin
Enqueue (Job);
end Load;
function Create_Loader
(Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr
is (new KTX_Loader'(Manager => Manager));
-----------------------------------------------------------------------------
-- Writer --
-----------------------------------------------------------------------------
procedure Write_Texture
(Texture : GL.Objects.Textures.Texture;
Location : Locations.Writable_Location_Ptr;
Path : String)
is
package Textures renames GL.Objects.Textures;
package Pointers is new Textures.Texture_Pointers (Byte_Pointers);
Format : GL.Pixels.Format := GL.Pixels.RGBA;
Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float;
-- Note: unused if texture is compressed
Base_Level : constant := 0;
use Ada.Streams;
use all type GL.Low_Level.Enums.Texture_Kind;
use type GL.Types.Size;
Compressed : constant Boolean := Texture.Compressed;
Header : Orka.KTX.Header (Compressed);
function Convert
(Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer
is
Pointer : Byte_Array_Pointers.Pointer;
Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length);
procedure Free is new Ada.Unchecked_Deallocation
(Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access);
begin
for Index in Bytes'Range loop
declare
Target_Index : constant Stream_Element_Offset
:= Stream_Element_Offset (Index - Bytes'First + 1);
begin
Result (Target_Index) := Stream_Element (Bytes (Index));
end;
end loop;
Free (Bytes);
Pointer.Set (Result);
return Pointer;
end Convert;
function Convert
(Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer
is
Pointer : Byte_Array_Pointers.Pointer;
Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length);
begin
Result.all := Bytes.all;
Pointers.Free (Bytes);
Pointer.Set (Result);
return Pointer;
end Convert;
function Get_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is
Data : Pointers.Element_Array_Access;
begin
Data := Pointers.Get_Data (Texture, Level, 0, 0, 0,
Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level),
Format, Data_Type);
return Convert (Data);
end Get_Data;
function Get_Compressed_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is
Data : GL.Types.UByte_Array_Access;
begin
Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0,
Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level),
Texture.Compressed_Format);
return Convert (Data);
end Get_Compressed_Data;
begin
Header.Kind := Texture.Kind;
Header.Width := Texture.Width (Base_Level);
case Texture.Kind is
when Texture_3D =>
Header.Height := Texture.Height (Base_Level);
Header.Depth := Texture.Depth (Base_Level);
when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array =>
Header.Height := Texture.Height (Base_Level);
Header.Depth := 0;
when Texture_1D | Texture_1D_Array =>
Header.Height := 0;
Header.Depth := 0;
when others =>
raise Program_Error;
end case;
case Texture.Kind is
when Texture_1D_Array =>
Header.Array_Elements := Texture.Height (Base_Level);
when Texture_2D_Array =>
Header.Array_Elements := Texture.Depth (Base_Level);
when Texture_Cube_Map_Array =>
Header.Array_Elements := Texture.Depth (Base_Level) / 6;
when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map =>
Header.Array_Elements := 0;
when others =>
raise Program_Error;
end case;
Header.Mipmap_Levels := Texture.Mipmap_Levels;
Header.Bytes_Key_Value := 0;
if Compressed then
Header.Compressed_Format := Texture.Compressed_Format;
else
declare
Internal_Format : constant GL.Pixels.Internal_Format
:= Texture.Internal_Format;
begin
Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind);
Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind);
Header.Internal_Format := Internal_Format;
Header.Format := Format;
Header.Data_Type := Data_Type;
end;
end if;
declare
function Get_Level_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level));
Bytes : constant Byte_Array_Pointers.Pointer
:= Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access);
begin
Location.Write_Data (Path, Bytes.Get);
end;
end Write_Texture;
end Orka.Resources.Textures.KTX;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Unchecked_Deallocation;
with GL.Low_Level.Enums;
with GL.Types;
with GL.Pixels.Queries;
with Orka.Logging;
with Orka.KTX;
package body Orka.Resources.Textures.KTX is
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Resource_Loader);
type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record
Data : Loaders.Resource_Data;
Manager : Managers.Manager_Ptr;
end record;
overriding
procedure Execute
(Object : KTX_Load_Job;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr));
-----------------------------------------------------------------------------
use all type Ada.Real_Time.Time;
overriding
procedure Execute
(Object : KTX_Load_Job;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr))
is
Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get;
Path : String renames SU.To_String (Object.Data.Path);
T1 : Ada.Real_Time.Time renames Object.Data.Start_Time;
T2 : constant Ada.Real_Time.Time := Clock;
use Ada.Streams;
use GL.Low_Level.Enums;
use type GL.Types.Size;
T3, T4, T5, T6 : Ada.Real_Time.Time;
begin
if not Orka.KTX.Valid_Identifier (Bytes) then
raise Texture_Load_Error with Path & " is not a KTX file";
end if;
declare
Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes);
Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels);
Resource : constant Texture_Ptr := new Texture'(others => <>);
Texture : GL.Objects.Textures.Texture (Header.Kind);
Width : constant GL.Types.Size := Header.Width;
Height : GL.Types.Size := Header.Height;
Depth : GL.Types.Size := Header.Depth;
begin
T3 := Clock;
-- Allocate storage
case Header.Kind is
when Texture_2D_Array =>
Depth := Header.Array_Elements;
when Texture_1D_Array =>
Height := Header.Array_Elements;
pragma Assert (Depth = 0);
when Texture_Cube_Map_Array =>
-- For a cube map array, depth is the number of layer-faces
Depth := Header.Array_Elements * 6;
when Texture_3D =>
null;
when Texture_2D | Texture_Cube_Map =>
pragma Assert (Depth = 0);
when Texture_1D =>
if Header.Compressed then
raise Texture_Load_Error with Path & " has unknown 1D compressed format";
end if;
pragma Assert (Height = 0);
pragma Assert (Depth = 0);
when others =>
raise Program_Error;
end case;
if Header.Compressed then
Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format,
Width, Height, Depth);
else
Texture.Allocate_Storage (Levels, 1, Header.Internal_Format,
Width, Height, Depth);
end if;
case Header.Kind is
when Texture_1D =>
Height := 1;
Depth := 1;
when Texture_1D_Array | Texture_2D =>
Depth := 1;
when Texture_2D_Array | Texture_3D =>
null;
when Texture_Cube_Map | Texture_Cube_Map_Array =>
-- Texture_Cube_Map uses 2D storage, but 3D load operation
-- according to table 8.15 of the OpenGL specification
-- For a cube map, depth is the number of faces, for
-- a cube map array, depth is the number of layer-faces
Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6;
when others =>
raise Program_Error;
end case;
T4 := Clock;
-- TODO Handle KTXorientation key value pair
-- Upload texture data
declare
Image_Size_Index : Stream_Element_Offset
:= Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value);
Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map;
begin
for Level in 0 .. Levels - 1 loop
declare
Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index);
-- If not Cube_Map, then Face_Size is the size of the whole level
Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4);
Image_Size : constant Natural
:= (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size);
-- If Cube_Map then Levels = 1 so no need to add it to the expression
-- Compute size of the whole mipmap level
Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4);
Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding;
Offset : constant Stream_Element_Offset := Image_Size_Index + 4;
pragma Assert
(Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last);
Image_Data : constant System.Address := Bytes (Offset)'Address;
-- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4
-- depending on Header.Data_Type
Level_Width : constant GL.Types.Size := Texture.Width (Level);
Level_Height : constant GL.Types.Size := Texture.Height (Level);
Level_Depth : constant GL.Types.Size := Texture.Depth (Level);
begin
if Header.Compressed then
Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth,
Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data);
else
Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth,
Header.Format, Header.Data_Type, Image_Data);
end if;
Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size);
end;
end loop;
end;
T5 := Clock;
-- Generate a full mipmap pyramid if Mipmap_Levels = 0
if Header.Mipmap_Levels = 0 then
Texture.Generate_Mipmap;
end if;
T6 := Clock;
Resource.Texture.Replace_Element (Texture);
-- Register resource at the resource manager
Object.Manager.Add_Resource (Path, Resource_Ptr (Resource));
Messages.Insert (Info, "Loaded texture " & Path & " in " &
Logging.Trim (Logging.Image (T6 - T1)));
Messages.Insert (Info, " size: " &
Logging.Trim (Width'Image) & " x " &
Logging.Trim (Height'Image) & " x " &
Logging.Trim (Depth'Image) &
", mipmap levels:" & Levels'Image);
Messages.Insert (Info, " kind: " & Header.Kind'Image);
if Header.Compressed then
Messages.Insert (Info, " format: " & Header.Compressed_Format'Image);
else
Messages.Insert (Info, " format: " & Header.Internal_Format'Image);
end if;
Messages.Insert (Info, " statistics:");
Messages.Insert (Info, " reading file: " & Logging.Image (T2 - T1));
Messages.Insert (Info, " parsing header: " & Logging.Image (T3 - T2));
Messages.Insert (Info, " storage: " & Logging.Image (T4 - T3));
Messages.Insert (Info, " buffers: " & Logging.Image (T5 - T4));
if Header.Mipmap_Levels = 0 then
Messages.Insert (Info, " generating mipmap:" & Logging.Image (T6 - T5));
end if;
end;
exception
when Error : Orka.KTX.Invalid_Enum_Error =>
declare
Message : constant String := Ada.Exceptions.Exception_Message (Error);
begin
raise Texture_Load_Error with Path & " has " & Message;
end;
end Execute;
-----------------------------------------------------------------------------
-- Loader --
-----------------------------------------------------------------------------
type KTX_Loader is limited new Loaders.Loader with record
Manager : Managers.Manager_Ptr;
end record;
overriding
function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx");
overriding
procedure Load
(Object : KTX_Loader;
Data : Loaders.Resource_Data;
Enqueue : not null access procedure (Element : Jobs.Job_Ptr);
Location : Locations.Location_Ptr)
is
Job : constant Jobs.Job_Ptr := new KTX_Load_Job'
(Jobs.Abstract_Job with
Data => Data,
Manager => Object.Manager);
begin
Enqueue (Job);
end Load;
function Create_Loader
(Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr
is (new KTX_Loader'(Manager => Manager));
-----------------------------------------------------------------------------
-- Writer --
-----------------------------------------------------------------------------
procedure Write_Texture
(Texture : GL.Objects.Textures.Texture;
Location : Locations.Writable_Location_Ptr;
Path : String)
is
package Textures renames GL.Objects.Textures;
package Pointers is new Textures.Texture_Pointers (Byte_Pointers);
Format : GL.Pixels.Format := GL.Pixels.RGBA;
Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float;
-- Note: unused if texture is compressed
Base_Level : constant := 0;
use Ada.Streams;
use all type GL.Low_Level.Enums.Texture_Kind;
use type GL.Types.Size;
Compressed : constant Boolean := Texture.Compressed;
Header : Orka.KTX.Header (Compressed);
function Convert
(Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer
is
Pointer : Byte_Array_Pointers.Pointer;
Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length);
procedure Free is new Ada.Unchecked_Deallocation
(Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access);
begin
for Index in Bytes'Range loop
declare
Target_Index : constant Stream_Element_Offset
:= Stream_Element_Offset (Index - Bytes'First + 1);
begin
Result (Target_Index) := Stream_Element (Bytes (Index));
end;
end loop;
Free (Bytes);
Pointer.Set (Result);
return Pointer;
end Convert;
function Convert
(Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer
is
Pointer : Byte_Array_Pointers.Pointer;
Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length);
begin
Result.all := Bytes.all;
Pointers.Free (Bytes);
Pointer.Set (Result);
return Pointer;
end Convert;
function Get_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is
Data : Pointers.Element_Array_Access;
begin
Data := Pointers.Get_Data (Texture, Level, 0, 0, 0,
Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level),
Format, Data_Type);
return Convert (Data);
end Get_Data;
function Get_Compressed_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is
Data : GL.Types.UByte_Array_Access;
begin
Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0,
Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level),
Texture.Compressed_Format);
return Convert (Data);
end Get_Compressed_Data;
begin
Header.Kind := Texture.Kind;
Header.Width := Texture.Width (Base_Level);
case Texture.Kind is
when Texture_3D =>
Header.Height := Texture.Height (Base_Level);
Header.Depth := Texture.Depth (Base_Level);
when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array =>
Header.Height := Texture.Height (Base_Level);
Header.Depth := 0;
when Texture_1D | Texture_1D_Array =>
Header.Height := 0;
Header.Depth := 0;
when others =>
raise Program_Error;
end case;
case Texture.Kind is
when Texture_1D_Array =>
Header.Array_Elements := Texture.Height (Base_Level);
when Texture_2D_Array =>
Header.Array_Elements := Texture.Depth (Base_Level);
when Texture_Cube_Map_Array =>
Header.Array_Elements := Texture.Depth (Base_Level) / 6;
when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map =>
Header.Array_Elements := 0;
when others =>
raise Program_Error;
end case;
Header.Mipmap_Levels := Texture.Mipmap_Levels;
Header.Bytes_Key_Value := 0;
if Compressed then
Header.Compressed_Format := Texture.Compressed_Format;
else
declare
Internal_Format : constant GL.Pixels.Internal_Format
:= Texture.Internal_Format;
begin
Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind);
Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind);
Header.Internal_Format := Internal_Format;
Header.Format := Format;
Header.Data_Type := Data_Type;
end;
end if;
declare
function Get_Level_Data
(Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer
is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level));
Bytes : constant Byte_Array_Pointers.Pointer
:= Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access);
begin
Location.Write_Data (Path, Bytes.Get);
end;
end Write_Texture;
end Orka.Resources.Textures.KTX;
|
Make some variables constant
|
orka: Make some variables constant
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
5aba17fd8803081517174cb999c60efb868b3169
|
src/os-linux/util-systems-dlls.adb
|
src/os-linux/util-systems-dlls.adb
|
-----------------------------------------------------------------------
-- util-systems-dlls -- Unix shared library support
-- 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Systems.Constants;
package body Util.Systems.DLLs is
function Sys_Dlopen (Path : in Interfaces.C.Strings.chars_ptr;
Mode : in Flags) return Handle;
pragma Import (C, Sys_Dlopen, "dlopen");
function Sys_Dlclose (Lib : in Handle) return Interfaces.C.int;
pragma Import (C, Sys_Dlclose, "dlclose");
function Sys_Dlsym (Lib : in Handle;
Symbol : in Interfaces.C.Strings.chars_ptr) return System.Address;
pragma Import (C, Sys_Dlsym, "dlsym");
function Sys_Dlerror return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Dlerror, "dlerror");
function Error_Message return String is
begin
return Interfaces.C.Strings.Value (Sys_Dlerror);
end Error_Message;
pragma Linker_Options ("-ldl");
-- -----------------------
-- Load the shared library with the given name or path and return a library handle.
-- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded.
-- -----------------------
function Load (Path : in String;
Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle is
Lib : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Result : Handle := Sys_Dlopen (Lib, Mode);
begin
Interfaces.C.Strings.Free (Lib);
if Result = Null_Handle then
raise Load_Error with Error_Message;
else
return Result;
end if;
end Load;
-- -----------------------
-- Unload the shared library.
-- -----------------------
procedure Unload (Lib : in Handle) is
Result : Interfaces.C.int;
begin
if Lib /= Null_Handle then
Result := Sys_Dlclose (Lib);
end if;
end Unload;
-- -----------------------
-- Get a global symbol with the given name in the library.
-- Raises the <tt>Not_Found</tt> exception if the symbol does not exist.
-- -----------------------
function Get_Symbol (Lib : in Handle;
Name : in String) return System.Address is
use type System.Address;
Symbol : Interfaces.C.Strings.Chars_Ptr := Interfaces.C.Strings.New_String (Name);
Result : System.Address := Sys_Dlsym (Lib, Symbol);
begin
Interfaces.C.Strings.Free (Symbol);
if Result = System.Null_Address then
raise Not_Found with Error_Message;
else
return Result;
end if;
end Get_Symbol;
end Util.Systems.DLLs;
|
-----------------------------------------------------------------------
-- util-systems-dlls -- Unix shared library support
-- 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Systems.Constants;
package body Util.Systems.DLLs is
function Sys_Dlopen (Path : in Interfaces.C.Strings.chars_ptr;
Mode : in Flags) return Handle;
pragma Import (C, Sys_Dlopen, "dlopen");
function Sys_Dlclose (Lib : in Handle) return Interfaces.C.int;
pragma Import (C, Sys_Dlclose, "dlclose");
function Sys_Dlsym (Lib : in Handle;
Symbol : in Interfaces.C.Strings.chars_ptr) return System.Address;
pragma Import (C, Sys_Dlsym, "dlsym");
function Sys_Dlerror return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Dlerror, "dlerror");
function Error_Message return String is
begin
return Interfaces.C.Strings.Value (Sys_Dlerror);
end Error_Message;
-- -----------------------
-- Load the shared library with the given name or path and return a library handle.
-- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded.
-- -----------------------
function Load (Path : in String;
Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle is
Lib : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Result : Handle := Sys_Dlopen (Lib, Mode);
begin
Interfaces.C.Strings.Free (Lib);
if Result = Null_Handle then
raise Load_Error with Error_Message;
else
return Result;
end if;
end Load;
-- -----------------------
-- Unload the shared library.
-- -----------------------
procedure Unload (Lib : in Handle) is
Result : Interfaces.C.int;
begin
if Lib /= Null_Handle then
Result := Sys_Dlclose (Lib);
end if;
end Unload;
-- -----------------------
-- Get a global symbol with the given name in the library.
-- Raises the <tt>Not_Found</tt> exception if the symbol does not exist.
-- -----------------------
function Get_Symbol (Lib : in Handle;
Name : in String) return System.Address is
use type System.Address;
Symbol : Interfaces.C.Strings.Chars_Ptr := Interfaces.C.Strings.New_String (Name);
Result : System.Address := Sys_Dlsym (Lib, Symbol);
begin
Interfaces.C.Strings.Free (Symbol);
if Result = System.Null_Address then
raise Not_Found with Error_Message;
else
return Result;
end if;
end Get_Symbol;
end Util.Systems.DLLs;
|
Move the linker option in the generated Util.Systems.Constants package
|
Move the linker option in the generated Util.Systems.Constants package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4f158d89e2c7772d1214c0302d413861d852b187
|
src/ado-drivers-connections.adb
|
src/ado-drivers-connections.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Driver : constant Driver_Access := Get_Driver (Config.Get_Driver);
begin
if Driver = null then
return Driver_Index'First;
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
Log.Debug ("Loading driver {0}", Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Log.Info ("Initialising driver {0}", Lib);
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Debug ("Get driver {0}", Name);
if Name'Length = 0 then
return null;
end if;
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Driver : constant Driver_Access := Get_Driver (Config.Get_Driver);
begin
if Driver = null then
return Driver_Index'First;
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- ------------------------------
-- Get the database driver index.
-- ------------------------------
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
Dynamic_Load : constant String := Get_Config (ADO.Configs.DYNAMIC_DRIVER_LOAD);
begin
if Dynamic_Load /= "1" and Dynamic_Load /= "true" then
Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name);
return;
end if;
Log.Debug ("Loading driver '{0}' from {1}", Name, Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Log.Info ("Initialising driver {0}", Lib);
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Debug ("Get driver {0}", Name);
if Name'Length = 0 then
return null;
end if;
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
Check for DYNAMIC_DRIVER_LOAD configuration parameter to test if we are allowed to load dynamically a database driver
|
Check for DYNAMIC_DRIVER_LOAD configuration parameter to test if we are allowed to load dynamically a database driver
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f0c8c14d389a0066405429f0bf55febf07c8b7ff
|
src/glfw/glfw-input-keys.ads
|
src/glfw/glfw-input-keys.ads
|
-- Copyright (c) 2013 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package Glfw.Input.Keys is
pragma Preelaborate;
type Action is (Release, Press, Repeat);
type Key is (Unknown,
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Key_0,
Key_1,
Key_2,
Key_3,
Key_4,
Key_5,
Key_6,
Key_7,
Key_8,
Key_9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Left_Bracket,
Backslash,
Right_Bracket,
Grave_Accent,
World_1,
World_2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
Page_Up,
Page_Down,
Home,
Key_End,
Caps_Lock,
Scroll_Lock,
Print_Screen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Numpad_0,
Numpad_1,
Numpad_2,
Numpad_3,
Numpad_4,
Numpad_5,
Numpad_6,
Numpad_7,
Numpad_8,
Numpad_9,
Numpad_Decimal,
Numpad_Divide,
Numpad_Multiply,
Numpad_Substract,
Numpad_Add,
Numpad_Enter,
Numpad_Equal,
Left_Shift,
Left_Control,
Left_Alt,
Left_Super,
Right_Shift,
Right_Control,
Right_Alt,
Right_Super,
Menu);
type Modifiers is record
Shift : Boolean;
Control : Boolean;
Alt : Boolean;
Super : Boolean;
end record;
type Scancode is new Interfaces.C.int;
private
for Action use (Release => 0,
Press => 1,
Repeat => 2);
for Action'Size use Interfaces.C.int'Size;
for Key use (Unknown => -1,
Space => 32,
Apostrophe => 39,
Comma => 44,
Minus => 45,
Period => 46,
Slash => 47,
Key_0 => 48,
Key_1 => 49,
Key_2 => 50,
Key_3 => 51,
Key_4 => 52,
Key_5 => 53,
Key_6 => 54,
Key_7 => 55,
Key_8 => 56,
Key_9 => 57,
Semicolon => 59,
Equal => 61,
A => 65,
B => 66,
C => 67,
D => 68,
E => 69,
F => 70,
G => 71,
H => 72,
I => 73,
J => 74,
K => 75,
L => 76,
M => 77,
N => 78,
O => 79,
P => 80,
Q => 81,
R => 82,
S => 83,
T => 84,
U => 85,
V => 86,
W => 87,
X => 88,
Y => 89,
Z => 90,
Left_Bracket => 91,
Backslash => 92,
Right_Bracket => 93,
Grave_Accent => 96,
World_1 => 161,
World_2 => 162,
Escape => 256,
Enter => 257,
Tab => 258,
Backspace => 259,
Insert => 260,
Delete => 261,
Right => 262,
Left => 263,
Down => 264,
Up => 265,
Page_Up => 266,
Page_Down => 267,
Home => 268,
Key_End => 269,
Caps_Lock => 280,
Scroll_Lock => 281,
Print_Screen => 283,
Pause => 284,
F1 => 290,
F2 => 291,
F3 => 292,
F4 => 293,
F5 => 294,
F6 => 295,
F7 => 296,
F8 => 297,
F9 => 298,
F10 => 299,
F11 => 300,
F12 => 301,
F13 => 302,
F14 => 303,
F15 => 304,
F16 => 305,
F17 => 306,
F18 => 307,
F19 => 308,
F20 => 309,
F21 => 310,
F22 => 311,
F23 => 312,
F24 => 313,
F25 => 314,
Numpad_0 => 320,
Numpad_1 => 321,
Numpad_2 => 322,
Numpad_3 => 323,
Numpad_4 => 324,
Numpad_5 => 325,
Numpad_6 => 326,
Numpad_7 => 327,
Numpad_8 => 328,
Numpad_9 => 329,
Numpad_Decimal => 330,
Numpad_Divide => 331,
Numpad_Multiply => 332,
Numpad_Substract => 333,
Numpad_Add => 334,
Numpad_Enter => 335,
Numpad_Equal => 336,
Left_Shift => 340,
Left_Control => 341,
Left_Alt => 342,
Left_Super => 343,
Right_Shift => 344,
Right_Control => 345,
Right_Alt => 346,
Right_Super => 347,
Menu => 348);
for Key'Size use Interfaces.C.int'Size;
for Modifiers use record
Shift at 0 range 0 .. 0;
Control at 0 range 1 .. 1;
Alt at 0 range 2 .. 2;
Super at 0 range 3 .. 3;
end record;
pragma Warnings (Off);
for Modifiers'Size use Interfaces.C.int'Size;
pragma Warnings (On);
pragma Convention (C_Pass_By_Copy, Modifiers);
for Scancode'Size use Interfaces.C.int'Size;
end Glfw.Input.Keys;
|
-- Copyright (c) 2013 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package Glfw.Input.Keys is
pragma Preelaborate;
type Action is (Release, Press, Repeat);
type Key is (Unknown,
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Key_0,
Key_1,
Key_2,
Key_3,
Key_4,
Key_5,
Key_6,
Key_7,
Key_8,
Key_9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Left_Bracket,
Backslash,
Right_Bracket,
Grave_Accent,
World_1,
World_2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
Page_Up,
Page_Down,
Home,
Key_End,
Caps_Lock,
Scroll_Lock,
Num_Lock,
Print_Screen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Numpad_0,
Numpad_1,
Numpad_2,
Numpad_3,
Numpad_4,
Numpad_5,
Numpad_6,
Numpad_7,
Numpad_8,
Numpad_9,
Numpad_Decimal,
Numpad_Divide,
Numpad_Multiply,
Numpad_Substract,
Numpad_Add,
Numpad_Enter,
Numpad_Equal,
Left_Shift,
Left_Control,
Left_Alt,
Left_Super,
Right_Shift,
Right_Control,
Right_Alt,
Right_Super,
Menu);
type Modifiers is record
Shift : Boolean;
Control : Boolean;
Alt : Boolean;
Super : Boolean;
end record;
type Scancode is new Interfaces.C.int;
private
for Action use (Release => 0,
Press => 1,
Repeat => 2);
for Action'Size use Interfaces.C.int'Size;
for Key use (Unknown => -1,
Space => 32,
Apostrophe => 39,
Comma => 44,
Minus => 45,
Period => 46,
Slash => 47,
Key_0 => 48,
Key_1 => 49,
Key_2 => 50,
Key_3 => 51,
Key_4 => 52,
Key_5 => 53,
Key_6 => 54,
Key_7 => 55,
Key_8 => 56,
Key_9 => 57,
Semicolon => 59,
Equal => 61,
A => 65,
B => 66,
C => 67,
D => 68,
E => 69,
F => 70,
G => 71,
H => 72,
I => 73,
J => 74,
K => 75,
L => 76,
M => 77,
N => 78,
O => 79,
P => 80,
Q => 81,
R => 82,
S => 83,
T => 84,
U => 85,
V => 86,
W => 87,
X => 88,
Y => 89,
Z => 90,
Left_Bracket => 91,
Backslash => 92,
Right_Bracket => 93,
Grave_Accent => 96,
World_1 => 161,
World_2 => 162,
Escape => 256,
Enter => 257,
Tab => 258,
Backspace => 259,
Insert => 260,
Delete => 261,
Right => 262,
Left => 263,
Down => 264,
Up => 265,
Page_Up => 266,
Page_Down => 267,
Home => 268,
Key_End => 269,
Caps_Lock => 280,
Scroll_Lock => 281,
Num_Lock => 282,
Print_Screen => 283,
Pause => 284,
F1 => 290,
F2 => 291,
F3 => 292,
F4 => 293,
F5 => 294,
F6 => 295,
F7 => 296,
F8 => 297,
F9 => 298,
F10 => 299,
F11 => 300,
F12 => 301,
F13 => 302,
F14 => 303,
F15 => 304,
F16 => 305,
F17 => 306,
F18 => 307,
F19 => 308,
F20 => 309,
F21 => 310,
F22 => 311,
F23 => 312,
F24 => 313,
F25 => 314,
Numpad_0 => 320,
Numpad_1 => 321,
Numpad_2 => 322,
Numpad_3 => 323,
Numpad_4 => 324,
Numpad_5 => 325,
Numpad_6 => 326,
Numpad_7 => 327,
Numpad_8 => 328,
Numpad_9 => 329,
Numpad_Decimal => 330,
Numpad_Divide => 331,
Numpad_Multiply => 332,
Numpad_Substract => 333,
Numpad_Add => 334,
Numpad_Enter => 335,
Numpad_Equal => 336,
Left_Shift => 340,
Left_Control => 341,
Left_Alt => 342,
Left_Super => 343,
Right_Shift => 344,
Right_Control => 345,
Right_Alt => 346,
Right_Super => 347,
Menu => 348);
for Key'Size use Interfaces.C.int'Size;
for Modifiers use record
Shift at 0 range 0 .. 0;
Control at 0 range 1 .. 1;
Alt at 0 range 2 .. 2;
Super at 0 range 3 .. 3;
end record;
pragma Warnings (Off);
for Modifiers'Size use Interfaces.C.int'Size;
pragma Warnings (On);
pragma Convention (C_Pass_By_Copy, Modifiers);
for Scancode'Size use Interfaces.C.int'Size;
end Glfw.Input.Keys;
|
Add missing Num_Lock key
|
glfw: Add missing Num_Lock key
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
f46babc8e2113cc03f3937def6f2ad69a3a90c69
|
src/util-beans-objects-records.adb
|
src/util-beans-objects-records.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Records -- Generic Typed Data Representation
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Records is
use Util.Concurrent.Counters;
-- ------------------------------
-- Bean Type
-- ------------------------------
type Record_Bean_Type is new Bean_Type with null record;
-- Get the type name
function Get_Name (Type_Def : in Record_Bean_Type) return String;
-- Convert the value into a boolean.
function To_Boolean (Type_Def : in Record_Bean_Type;
Value : in Object_Value) return Boolean;
-- ------------------------------
-- Get the type name
-- ------------------------------
function Get_Name (Type_Def : in Record_Bean_Type) return String is
pragma Unreferenced (Type_Def);
begin
return "Bean_Record";
end Get_Name;
-- ------------------------------
-- Convert the value into a boolean.
-- ------------------------------
function To_Boolean (Type_Def : in Record_Bean_Type;
Value : in Object_Value) return Boolean is
pragma Unreferenced (Type_Def);
begin
return Value.Proxy /= null;
end To_Boolean;
Bn_Type : aliased Record_Bean_Type := Record_Bean_Type '(others => <>);
-- ------------------------------
-- Create an object which holds a record of the type <b>Element_Type</b>.
-- ------------------------------
function Create return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_BEAN,
Proxy => new Element_Proxy '(Ref_Counter => ONE,
others => <>)),
Type_Def => Bn_Type'Access);
end Create;
-- ------------------------------
-- Create an object which is initialized with the given value.
-- ------------------------------
function To_Object (Value : in Element_Type) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_BEAN,
Proxy => new Element_Proxy '(Ref_Counter => ONE,
Value => Value)),
Type_Def => Bn_Type'Access);
end To_Object;
-- ------------------------------
-- Returns the element
-- ------------------------------
function To_Element (Value : in Object) return Element_Type is
begin
if Value.V.Of_Type /= TYPE_BEAN then
raise Conversion_Error with "Object is not a bean";
end if;
declare
Proxy : constant Bean_Proxy_Access := Value.V.Proxy;
begin
if Proxy = null then
raise Conversion_Error with "Object is null";
end if;
if not (Proxy.all in Element_Proxy'Class) then
raise Conversion_Error with "Object is not of the good type";
end if;
return Element_Proxy'Class (Proxy.all).Value;
end;
end To_Element;
-- ------------------------------
-- Returns an access to the element.
-- ------------------------------
function To_Element_Access (Value : in Object) return Element_Type_Access is
begin
if Value.V.Of_Type /= TYPE_BEAN then
return null;
end if;
declare
Proxy : constant Bean_Proxy_Access := Value.V.Proxy;
begin
if Proxy = null then
return null;
end if;
if not (Proxy.all in Element_Proxy'Class) then
return null;
end if;
return Element_Proxy'Class (Proxy.all).Value'Access;
end;
end To_Element_Access;
end Util.Beans.Objects.Records;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Records -- Generic Typed Data Representation
-- Copyright (C) 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.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Records is
use Util.Concurrent.Counters;
-- ------------------------------
-- Bean Type
-- ------------------------------
type Record_Bean_Type is new Bean_Type with null record;
-- Get the type name
function Get_Name (Type_Def : in Record_Bean_Type) return String;
-- Convert the value into a boolean.
function To_Boolean (Type_Def : in Record_Bean_Type;
Value : in Object_Value) return Boolean;
-- ------------------------------
-- Get the type name
-- ------------------------------
function Get_Name (Type_Def : in Record_Bean_Type) return String is
pragma Unreferenced (Type_Def);
begin
return "Bean_Record";
end Get_Name;
-- ------------------------------
-- Convert the value into a boolean.
-- ------------------------------
function To_Boolean (Type_Def : in Record_Bean_Type;
Value : in Object_Value) return Boolean is
pragma Unreferenced (Type_Def);
begin
return Value.Proxy /= null;
end To_Boolean;
Bn_Type : aliased Record_Bean_Type := Record_Bean_Type '(null record);
-- ------------------------------
-- Create an object which holds a record of the type <b>Element_Type</b>.
-- ------------------------------
function Create return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_BEAN,
Proxy => new Element_Proxy '(Ref_Counter => ONE,
others => <>)),
Type_Def => Bn_Type'Access);
end Create;
-- ------------------------------
-- Create an object which is initialized with the given value.
-- ------------------------------
function To_Object (Value : in Element_Type) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_BEAN,
Proxy => new Element_Proxy '(Ref_Counter => ONE,
Value => Value)),
Type_Def => Bn_Type'Access);
end To_Object;
-- ------------------------------
-- Returns the element
-- ------------------------------
function To_Element (Value : in Object) return Element_Type is
begin
if Value.V.Of_Type /= TYPE_BEAN then
raise Conversion_Error with "Object is not a bean";
end if;
declare
Proxy : constant Bean_Proxy_Access := Value.V.Proxy;
begin
if Proxy = null then
raise Conversion_Error with "Object is null";
end if;
if not (Proxy.all in Element_Proxy'Class) then
raise Conversion_Error with "Object is not of the good type";
end if;
return Element_Proxy'Class (Proxy.all).Value;
end;
end To_Element;
-- ------------------------------
-- Returns an access to the element.
-- ------------------------------
function To_Element_Access (Value : in Object) return Element_Type_Access is
begin
if Value.V.Of_Type /= TYPE_BEAN then
return null;
end if;
declare
Proxy : constant Bean_Proxy_Access := Value.V.Proxy;
begin
if Proxy = null then
return null;
end if;
if not (Proxy.all in Element_Proxy'Class) then
return null;
end if;
return Element_Proxy'Class (Proxy.all).Value'Access;
end;
end To_Element_Access;
end Util.Beans.Objects.Records;
|
Fix new GNAT compilation warning in initialization records: use null record
|
Fix new GNAT compilation warning in initialization records: use null record
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e989a8d92c56f3f2c63c905fb6e452d33de69a73
|
regtests/util-beans-objects-discretes.adb
|
regtests/util-beans-objects-discretes.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Discretes -- Unit tests for concurrency package
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Util.Beans.Objects;
with Util.Beans.Objects.Enums;
with Util.Beans.Objects.Time;
with Util.Beans.Objects.Discrete_Tests;
package body Util.Beans.Objects.Discretes is
use Ada.Calendar;
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function Time_Value (S : String) return Ada.Calendar.Time;
function "-" (Left, Right : Boolean) return Boolean;
function "+" (Left, Right : Boolean) return Boolean;
package Test_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Integer,
To_Type => Util.Beans.Objects.To_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Integer'Value,
Test_Name => "Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Integer'Value,
Test_Name => "Long_Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Integer'Value,
Test_Name => "Long_Long_Integer",
Test_Values => "-10000000000000,1,0,1,1000_000_000_000");
function "-" (Left, Right : Boolean) return Boolean is
begin
return Left and Right;
end "-";
function "+" (Left, Right : Boolean) return Boolean is
begin
return Left or Right;
end "+";
package Test_Boolean is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Boolean,
To_Type => Util.Beans.Objects.To_Boolean,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Boolean'Value,
Test_Name => "Boolean",
Test_Values => "false,true");
type Color is (WHITE, BLACK, RED, GREEN, BLUE, YELLOW);
package Color_Object is new Util.Beans.Objects.Enums (Color, ROUND_VALUE => True);
function "-" (Left, Right : Color) return Color;
function "+" (Left, Right : Color) return Color;
function "-" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) - Color'Pos (Right);
begin
if N >= 0 then
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
else
return Color'Val ((Color'Pos (WHITE) - N) mod 6);
end if;
end "-";
function "+" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) + Color'Pos (Right);
begin
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
end "+";
package Test_Enum is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Color,
To_Type => Color_Object.To_Value,
To_Object_Test => Color_Object.To_Object,
Value => Color'Value,
Test_Name => "Color",
Test_Values => "BLACK,RED,GREEN,BLUE,YELLOW");
Epoch : constant Ada.Calendar.Time :=
Ada.Calendar.Time_Of (Year => Year_Number'First,
Month => 1,
Day => 1,
Seconds => 12 * 3600.0);
function Time_Value (S : String) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Value (S);
end Time_Value;
-- For the purpose of the time unit test, we need Time + Time operation even
-- if this does not really makes sense.
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 + T2) + Epoch;
end "+";
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 - T2) + Epoch;
end "-";
package Test_Time is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Ada.Calendar.Time,
To_Type => Util.Beans.Objects.Time.To_Time,
To_Object_Test => Util.Beans.Objects.Time.To_Object,
Value => Time_Value,
Test_Name => "Time",
Test_Values => "1970-03-04 12:12:00,1975-05-04 13:13:10");
package Test_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Float,
To_Type => Util.Beans.Objects.To_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Float'Value,
Test_Name => "Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Float,
To_Type => Util.Beans.Objects.To_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Float'Value,
Test_Name => "Long_Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Float,
To_Type => Util.Beans.Objects.To_Long_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Float'Value,
Test_Name => "Long_Long_Float",
Test_Values => "1.2,3.3,-3.3");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Test_Boolean.Add_Tests (Suite);
Test_Integer.Add_Tests (Suite);
Test_Long_Integer.Add_Tests (Suite);
Test_Long_Long_Integer.Add_Tests (Suite);
Test_Time.Add_Tests (Suite);
Test_Float.Add_Tests (Suite);
Test_Long_Float.Add_Tests (Suite);
Test_Long_Long_Float.Add_Tests (Suite);
Test_Enum.Add_Tests (Suite);
end Add_Tests;
end Util.Beans.Objects.Discretes;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Discretes -- Unit tests for concurrency package
-- Copyright (C) 2009, 2010, 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.Calendar;
with Ada.Calendar.Formatting;
with Util.Beans.Objects;
with Util.Beans.Objects.Enums;
with Util.Beans.Objects.Time;
with Util.Beans.Objects.Discrete_Tests;
package body Util.Beans.Objects.Discretes is
use Ada.Calendar;
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function Time_Value (S : String) return Ada.Calendar.Time;
function "-" (Left, Right : Boolean) return Boolean;
function "+" (Left, Right : Boolean) return Boolean;
package Test_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Integer,
To_Type => Util.Beans.Objects.To_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Integer'Value,
Test_Name => "Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Duration is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Duration,
To_Type => Util.Beans.Objects.To_Duration,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Duration'Value,
Test_Name => "Duration",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Integer'Value,
Test_Name => "Long_Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Integer'Value,
Test_Name => "Long_Long_Integer",
Test_Values => "-10000000000000,1,0,1,1000_000_000_000");
function "-" (Left, Right : Boolean) return Boolean is
begin
return Left and Right;
end "-";
function "+" (Left, Right : Boolean) return Boolean is
begin
return Left or Right;
end "+";
package Test_Boolean is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Boolean,
To_Type => Util.Beans.Objects.To_Boolean,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Boolean'Value,
Test_Name => "Boolean",
Test_Values => "false,true");
type Color is (WHITE, BLACK, RED, GREEN, BLUE, YELLOW);
package Color_Object is new Util.Beans.Objects.Enums (Color, ROUND_VALUE => True);
function "-" (Left, Right : Color) return Color;
function "+" (Left, Right : Color) return Color;
function "-" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) - Color'Pos (Right);
begin
if N >= 0 then
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
else
return Color'Val ((Color'Pos (WHITE) - N) mod 6);
end if;
end "-";
function "+" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) + Color'Pos (Right);
begin
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
end "+";
package Test_Enum is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Color,
To_Type => Color_Object.To_Value,
To_Object_Test => Color_Object.To_Object,
Value => Color'Value,
Test_Name => "Color",
Test_Values => "BLACK,RED,GREEN,BLUE,YELLOW");
Epoch : constant Ada.Calendar.Time :=
Ada.Calendar.Time_Of (Year => Year_Number'First,
Month => 1,
Day => 1,
Seconds => 12 * 3600.0);
function Time_Value (S : String) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Value (S);
end Time_Value;
-- For the purpose of the time unit test, we need Time + Time operation even
-- if this does not really makes sense.
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 + T2) + Epoch;
end "+";
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 - T2) + Epoch;
end "-";
package Test_Time is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Ada.Calendar.Time,
To_Type => Util.Beans.Objects.Time.To_Time,
To_Object_Test => Util.Beans.Objects.Time.To_Object,
Value => Time_Value,
Test_Name => "Time",
Test_Values => "1970-03-04 12:12:00,1975-05-04 13:13:10");
package Test_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Float,
To_Type => Util.Beans.Objects.To_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Float'Value,
Test_Name => "Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Float,
To_Type => Util.Beans.Objects.To_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Float'Value,
Test_Name => "Long_Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Float,
To_Type => Util.Beans.Objects.To_Long_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Float'Value,
Test_Name => "Long_Long_Float",
Test_Values => "1.2,3.3,-3.3");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Test_Boolean.Add_Tests (Suite);
Test_Integer.Add_Tests (Suite);
Test_Long_Integer.Add_Tests (Suite);
Test_Duration.Add_Tests (Suite);
Test_Long_Long_Integer.Add_Tests (Suite);
Test_Time.Add_Tests (Suite);
Test_Float.Add_Tests (Suite);
Test_Long_Float.Add_Tests (Suite);
Test_Long_Long_Float.Add_Tests (Suite);
Test_Enum.Add_Tests (Suite);
end Add_Tests;
end Util.Beans.Objects.Discretes;
|
Add Test_Duration to check Duration types
|
Add Test_Duration to check Duration types
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
75d21099228c550323d52bd2fbed8c67b353895e
|
samples/asf_volume_server.adb
|
samples/asf_volume_server.adb
|
-----------------------------------------------------------------------
-- asf_volume_server -- The volume_server application with Ada Server Faces
-- 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 ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Filters.Dump;
with ASF.Applications;
with ASF.Applications.Main;
with EL.Objects;
with Volume;
procedure Asf_Volume_Server is
CONTEXT_PATH : constant String := "/volume";
Factory : ASF.Applications.Main.Application_Factory;
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Bean : aliased Volume.Compute_Bean;
Conv : constant access Volume.Float_Converter := new Volume.Float_Converter;
WS : ASF.Server.Web.AWS_Container;
C : ASF.Applications.Config;
begin
Bean.Radius := 1.2;
Bean.Height := 2.0;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("compute", EL.Objects.To_Object (Bean'Unchecked_Access));
-- Register the servlets and filters
App.Add_Servlet (Name => "compute", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "compute", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Converter (Name => "float", Converter => Conv.all'Unchecked_Access);
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
WS.Start;
delay 600.0;
end Asf_Volume_Server;
|
-----------------------------------------------------------------------
-- asf_volume_server -- The volume_server application with Ada Server Faces
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Server.Web;
with ASF.Servlets;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Filters.Dump;
with ASF.Applications;
with ASF.Applications.Main;
with Util.Beans.Objects;
with Volume;
procedure Asf_Volume_Server is
CONTEXT_PATH : constant String := "/volume";
Factory : ASF.Applications.Main.Application_Factory;
App : aliased ASF.Applications.Main.Application;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Bean : aliased Volume.Compute_Bean;
Conv : constant access Volume.Float_Converter := new Volume.Float_Converter;
WS : ASF.Server.Web.AWS_Container;
C : ASF.Applications.Config;
begin
Bean.Radius := 1.2;
Bean.Height := 2.0;
C.Set (ASF.Applications.VIEW_EXT, ".html");
C.Set (ASF.Applications.VIEW_DIR, "samples/web");
C.Set ("web.dir", "samples/web");
App.Initialize (C, Factory);
App.Set_Global ("contextPath", CONTEXT_PATH);
App.Set_Global ("faces", Util.Beans.Objects.To_Object (Bean'Unchecked_Access));
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Converter (Name => "float", Converter => Conv.all'Unchecked_Access);
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
WS.Start;
delay 600.0;
end Asf_Volume_Server;
|
Rename servlet and cleanup
|
Rename servlet and cleanup
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
9428a9e44d7a9d295b918e6ea2b725d375f00d00
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- 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 Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
-- Query_List : Query_Definition_Access := null;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Into : in Query_File_Access) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Access;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
Into.Query := null;
if Into.Query_Def /= null then
Into.Query := new Query_Info;
Into.Query_Def.Query := Into.Query;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Reader, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all);
Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.File);
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Paths : in String;
Load : in Boolean) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Free (File.Path);
File.Path := new String '(Path);
if Load then
Read_Query (File);
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- 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 Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Into : in Query_File_Access) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Access;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
Into.Query := null;
if Into.Query_Def /= null then
Into.Query := new Query_Info;
Into.Query_Def.Query := Into.Query;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Reader, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all);
Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.File);
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Paths : in String;
Load : in Boolean) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Free (File.Path);
File.Path := new String '(Path);
if Load then
Read_Query (File);
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Remove unused code
|
Remove unused code
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
d23732bb063be95ed3b7dd022457402b94c7a690
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Into : in Query_File_Access) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Into.Query_Def.Query.Set (Into.Query);
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Reader, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all);
Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.File);
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Paths : in String;
Load : in Boolean) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
Query : Query_Definition_Access := File.Queries;
begin
Free (File.Path);
File.Path := new String '(Path);
-- Allocate the atomic reference for each query.
while Query /= null loop
if Query.Query = null then
Query.Query := new Query_Info_Ref.Atomic_Ref;
end if;
Query := Query.Next;
end loop;
if Load then
Read_Query (File);
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ADO.Drivers.Connections;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Into : in Query_File_Access) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Into.Query_Def.Query.Set (Into.Query);
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Mapper, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all, Mapper);
Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.File);
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Paths : in String;
Load : in Boolean) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String,
Name => Ada.Strings.Unbounded.String_Access);
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
Query : Query_Definition_Access := File.Queries;
begin
Free (File.Path);
File.Path := new String '(Path);
-- Allocate the atomic reference for each query.
while Query /= null loop
if Query.Query = null then
Query.Query := new Query_Info_Ref.Atomic_Ref;
end if;
Query := Query.Next;
end loop;
if Load then
Read_Query (File);
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Update parsing the XML query to use the new parser/mapper interfaces
|
Update parsing the XML query to use the new parser/mapper interfaces
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
424cf346ce7e65f698154bf7de9a945d20d352fa
|
src/asf-beans-resolvers.adb
|
src/asf-beans-resolvers.adb
|
-----------------------------------------------------------------------
-- asf-beans-resolvers -- Resolver to create and give access to managed beans
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Sessions;
with ASF.Beans.Params;
with ASF.Beans.Flash;
with ASF.Beans.Globals;
with ASF.Beans.Headers;
package body ASF.Beans.Resolvers is
-- ------------------------------
-- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>.
-- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam).
-- It then looks in the request and session attributes for the value. If the value was
-- not in the request or session, it uses the application bean factory to create the
-- new managed bean and adds it to the request or session.
-- ------------------------------
overriding
function Get_Value (Resolver : in ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String)
return Util.Beans.Objects.Object is
use type Util.Beans.Basic.Readonly_Bean_Access;
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
elsif Key = ASF.Beans.Params.PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Params.Instance;
elsif Key = ASF.Beans.Headers.HEADER_ATTRIBUTE_NAME then
return ASF.Beans.Headers.Instance;
elsif Key = ASF.Beans.Flash.FLASH_ATTRIBUTE_NAME then
return ASF.Beans.Flash.Instance;
elsif Key = ASF.Beans.Globals.INIT_PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Globals.Instance;
end if;
declare
Result : Util.Beans.Objects.Object;
Scope : Scope_Type;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- Look in the resolver's attributes first.
Pos : constant Util.Beans.Objects.Maps.Cursor := Resolver.Attributes.Find (Key);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
elsif Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
if Scope = SESSION_SCOPE then
Session.Set_Attribute (Name => Key,
Value => Result);
else
Resolver.Request.Set_Attribute (Name => Key,
Value => Result);
end if;
return Result;
end;
else
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
Resolver.Attributes_Access.Include (Key, Result);
return Result;
end if;
end;
end Get_Value;
-- ------------------------------
-- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>.
-- If there is no <tt>Base</tt> object, the request attribute with the given name is
-- updated to the given value.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
else
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
end if;
end Set_Value;
-- ------------------------------
-- Initialize the resolver.
-- ------------------------------
overriding
procedure Initialize (Resolver : in out ELResolver) is
begin
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
end ASF.Beans.Resolvers;
|
-----------------------------------------------------------------------
-- asf-beans-resolvers -- Resolver to create and give access to managed beans
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Sessions;
with ASF.Beans.Params;
with ASF.Beans.Flash;
with ASF.Beans.Globals;
with ASF.Beans.Headers;
package body ASF.Beans.Resolvers is
-- ------------------------------
-- Initialize the EL resolver to use the application bean factory and the given request.
-- ------------------------------
procedure Initialize (Resolver : in out ELResolver;
App : in ASF.Applications.Main.Application_Access;
Request : in ASF.Requests.Request_Access) is
begin
Resolver.Application := App;
Resolver.Request := Request;
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>.
-- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam).
-- It then looks in the request and session attributes for the value. If the value was
-- not in the request or session, it uses the application bean factory to create the
-- new managed bean and adds it to the request or session.
-- ------------------------------
overriding
function Get_Value (Resolver : in ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String)
return Util.Beans.Objects.Object is
use type Util.Beans.Basic.Readonly_Bean_Access;
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
elsif Key = ASF.Beans.Params.PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Params.Instance;
elsif Key = ASF.Beans.Headers.HEADER_ATTRIBUTE_NAME then
return ASF.Beans.Headers.Instance;
elsif Key = ASF.Beans.Flash.FLASH_ATTRIBUTE_NAME then
return ASF.Beans.Flash.Instance;
elsif Key = ASF.Beans.Globals.INIT_PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Globals.Instance;
end if;
declare
Result : Util.Beans.Objects.Object;
Scope : Scope_Type;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- Look in the resolver's attributes first.
Pos : constant Util.Beans.Objects.Maps.Cursor := Resolver.Attributes.Find (Key);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
elsif Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
if Scope = SESSION_SCOPE then
Session.Set_Attribute (Name => Key,
Value => Result);
else
Resolver.Request.Set_Attribute (Name => Key,
Value => Result);
end if;
return Result;
end;
else
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
Resolver.Attributes_Access.Include (Key, Result);
return Result;
end if;
end;
end Get_Value;
-- ------------------------------
-- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>.
-- If there is no <tt>Base</tt> object, the request attribute with the given name is
-- updated to the given value.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
else
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
end if;
end Set_Value;
-- ------------------------------
-- Initialize the resolver.
-- ------------------------------
overriding
procedure Initialize (Resolver : in out ELResolver) is
begin
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
end ASF.Beans.Resolvers;
|
Initialize the EL resolver to use the application bean factory and the given request.
|
Initialize the EL resolver to use the application bean factory and the
given request.
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
1413f7e0774a8c438baee15aef8ed9533632b4ed
|
src/babel-streams-files.ads
|
src/babel-streams-files.ads
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream 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.
-----------------------------------------------------------------------
private with Util.Streams.Raw;
-- == Local Files Stream ==
-- The <tt>Babel.Streams.Files</tt> package provides the streams support to read and write
-- local files.
package Babel.Streams.Files is
type Stream_Type is new Babel.Streams.Stream_Type with private;
type Stream_Access is access all Stream_Type'Class;
-- Open the local file for reading and use the given buffer for the Read operation.
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access);
-- Create a file and prepare for the Write operation.
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t);
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access);
-- Write the buffer in the data stream.
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access);
-- Close the data stream.
overriding
procedure Close (Stream : in out Stream_Type);
-- Prepare to read again the data stream from the beginning.
overriding
procedure Rewind (Stream : in out Stream_Type);
-- Set the internal buffer that the stream can use.
overriding
procedure Set_Buffer (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access);
private
type Stream_Type is new Babel.Streams.Stream_Type with record
File : Util.Streams.Raw.Raw_Stream;
Buffer : Babel.Files.Buffers.Buffer_Access;
Eof : Boolean := False;
end record;
end Babel.Streams.Files;
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream 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.
-----------------------------------------------------------------------
private with Util.Streams.Raw;
-- == Local Files Stream ==
-- The <tt>Babel.Streams.Files</tt> package provides the streams support to read and write
-- local files.
package Babel.Streams.Files is
type Stream_Type is new Babel.Streams.Stream_Type with private;
type Stream_Access is access all Stream_Type'Class;
-- Open the local file for reading and use the given buffer for the Read operation.
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access);
-- Create a file and prepare for the Write operation.
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t);
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access);
-- Write the buffer in the data stream.
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access);
-- Close the data stream.
overriding
procedure Close (Stream : in out Stream_Type);
-- Prepare to read again the data stream from the beginning.
overriding
procedure Rewind (Stream : in out Stream_Type);
private
type Stream_Type is new Babel.Streams.Stream_Type with record
File : Util.Streams.Raw.Raw_Stream;
Eof : Boolean := False;
end record;
end Babel.Streams.Files;
|
Remove the buffer from the Stream_Type record to use the root buffer
|
Remove the buffer from the Stream_Type record to use the root buffer
|
Ada
|
apache-2.0
|
stcarrez/babel
|
410f3806f5dfbffe2739270e0317060856dec208
|
awt/src/awt-drag_and_drop.ads
|
awt/src/awt-drag_and_drop.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with AWT.Inputs;
package AWT.Drag_And_Drop is
type Receive_Callback is access protected procedure (Value : SU.Unbounded_String);
use all type AWT.Inputs.Action_Kind;
function Supported_Actions return AWT.Inputs.Actions;
function Valid_Action return AWT.Inputs.Action_Kind;
-- Return the used action for the drag'n'drop operation
--
-- May be called in overriding procedure On_Drag of Window.
--
-- If the returned value is not None, then procedure Get can be called
-- or a signal can be set via a protected object, followed by a call
-- to function Get in the environment task.
procedure Set_Action (Action : AWT.Inputs.Action_Kind);
-- Set the requested action that must happen when the user
-- drops something on the current focused window
--
-- Should be called in the overriding procedure On_Drag of Window.
procedure Finish (Action : AWT.Inputs.Action_Kind)
with Pre => Action /= Ask and Valid_Action /= None;
-- Finish the current drag-and-drop operation.
--
-- To accept the operation, use Copy or Move. If the last set
-- action was Ask, then the value may either be Copy or Move,
-- otherwise it must match the last set action.
--
-- To reject the operation, use None.
procedure Get (Callback : not null Receive_Callback)
with Pre => Valid_Action /= None;
-- Receive data from a drag-and-drop operation
--
-- Before calling this procedure, call function Valid_Actions
-- to determine what kind of operation needs to take place. If "Ask" is
-- true, then the application may want to show menu to let the user
-- choose.
--
-- After the given callback has been executed, finish the operation
-- by calling Finish to accept or reject the received data.
function Get return String;
end AWT.Drag_And_Drop;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with AWT.Inputs;
package AWT.Drag_And_Drop is
type Receive_Callback is access protected procedure (Value : SU.Unbounded_String);
use all type AWT.Inputs.Action_Kind;
function Supported_Actions return AWT.Inputs.Actions;
function Valid_Action return AWT.Inputs.Action_Kind;
-- Return the used action for the drag'n'drop operation
--
-- May be called in overriding procedure On_Drop of Window.
--
-- If the returned value is not None, then procedure Get can be called
-- or a signal can be set via a protected object, followed by a call
-- to function Get in the environment task.
procedure Set_Action (Action : AWT.Inputs.Action_Kind);
-- Set the requested action that must happen when the user
-- drops something on the current focused window
--
-- Should be called in the overriding procedure On_Drag of Window.
procedure Finish (Action : AWT.Inputs.Action_Kind)
with Pre => Action /= Ask and Valid_Action /= None;
-- Finish the current drag-and-drop operation.
--
-- To accept the operation, use Copy or Move. If the last set
-- action was Ask, then the value may either be Copy or Move,
-- otherwise it must match the last set action.
--
-- To reject the operation, use None.
procedure Get (Callback : not null Receive_Callback)
with Pre => Valid_Action /= None;
-- Receive data from a drag-and-drop operation
--
-- Before calling this procedure, call function Supported_Actions
-- to determine what kind of operation needs to take place. If "Ask" is
-- true, then the application may want to show a menu to let the user
-- choose.
--
-- After the given callback has been executed, finish the operation
-- by calling Finish to accept or reject the received data.
function Get return String;
end AWT.Drag_And_Drop;
|
Fix some typos in comments in package AWT.Drag_And_Drop
|
awt: Fix some typos in comments in package AWT.Drag_And_Drop
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
b5d3106948411b21ec054abf7b9cea1964476853
|
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
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
4287a4d415e375fe93b59e4312b7c755a3ba19f1
|
awa/src/awa-events-queues.adb
|
awa/src/awa-events-queues.adb
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Serialize.Mappers;
with AWA.Events.Queues.Fifos;
with AWA.Events.Queues.Persistents;
package body AWA.Events.Queues is
-- ------------------------------
-- Queue the event.
-- ------------------------------
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class) is
Q : constant Queue_Info_Access := Into.Value;
begin
if Q = null or else Q.Queue = null then
return;
end if;
Q.Queue.Enqueue (Event);
end Enqueue;
-- ------------------------------
-- Dequeue an event and process it with the <b>Process</b> procedure.
-- ------------------------------
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class)) is
Q : constant Queue_Info_Access := From.Value;
begin
if Q = null or else Q.Queue = null then
return;
end if;
Q.Queue.Dequeue (Process);
end Dequeue;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Queue : in Queue_Ref'Class) return Boolean is
Q : constant Queue_Info_Access := Queue.Value;
begin
return Q = null or else Q.Queue = null;
end Is_Null;
-- ------------------------------
-- Returns the queue name.
-- ------------------------------
function Get_Name (Queue : in Queue_Ref'Class) return String is
Q : constant Queue_Info_Access := Queue.Value;
begin
if Q = null then
return "";
else
return Q.Name;
end if;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is
Q : constant Queue_Info_Access := Queue.Value;
begin
if Q = null or else Q.Queue = null then
return AWA.Events.Models.Null_Queue;
else
return Q.Queue.Get_Queue;
end if;
end Get_Queue;
FIFO_QUEUE_TYPE : constant String := "fifo";
PERSISTENT_QUEUE_TYPE : constant String := "persist";
-- ------------------------------
-- Create the event queue identified by the name <b>Name</b>. The queue factory
-- identified by <b>Kind</b> is called to create the event queue instance.
-- Returns a reference to the queue.
-- ------------------------------
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref is
Result : Queue_Ref;
Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with
Length => Name'Length,
Name => Name,
others => <>);
begin
Queue_Refs.Ref (Result) := Queue_Refs.Create (Q);
if Kind = FIFO_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Fifos.Create_Queue (Name, Props, Context);
elsif Name = PERSISTENT_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Persistents.Create_Queue (Name, Props, Context);
else
raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Name;
end if;
return Result;
end Create_Queue;
function Null_Queue return Queue_Ref is
Result : Queue_Ref;
begin
return Result;
end Null_Queue;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out Queue_Info) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Queue'Class,
Name => Queue_Access);
begin
if Object.Queue /= null then
Object.Queue.Finalize;
Free (Object.Queue);
end if;
end Finalize;
end AWA.Events.Queues;
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Serialize.Mappers;
with AWA.Events.Queues.Fifos;
with AWA.Events.Queues.Persistents;
package body AWA.Events.Queues is
-- ------------------------------
-- Queue the event.
-- ------------------------------
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class) is
Q : constant Queue_Info_Access := Into.Value;
begin
if Q = null or else Q.Queue = null then
return;
end if;
Q.Queue.Enqueue (Event);
end Enqueue;
-- ------------------------------
-- Dequeue an event and process it with the <b>Process</b> procedure.
-- ------------------------------
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class)) is
Q : constant Queue_Info_Access := From.Value;
begin
if Q = null or else Q.Queue = null then
return;
end if;
Q.Queue.Dequeue (Process);
end Dequeue;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Queue : in Queue_Ref'Class) return Boolean is
Q : constant Queue_Info_Access := Queue.Value;
begin
return Q = null or else Q.Queue = null;
end Is_Null;
-- ------------------------------
-- Returns the queue name.
-- ------------------------------
function Get_Name (Queue : in Queue_Ref'Class) return String is
Q : constant Queue_Info_Access := Queue.Value;
begin
if Q = null then
return "";
else
return Q.Name;
end if;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is
Q : constant Queue_Info_Access := Queue.Value;
begin
if Q = null or else Q.Queue = null then
return AWA.Events.Models.Null_Queue;
else
return Q.Queue.Get_Queue;
end if;
end Get_Queue;
FIFO_QUEUE_TYPE : constant String := "fifo";
PERSISTENT_QUEUE_TYPE : constant String := "persist";
-- ------------------------------
-- Create the event queue identified by the name <b>Name</b>. The queue factory
-- identified by <b>Kind</b> is called to create the event queue instance.
-- Returns a reference to the queue.
-- ------------------------------
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref is
Result : Queue_Ref;
Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with
Length => Name'Length,
Name => Name,
others => <>);
begin
Queue_Refs.Ref (Result) := Queue_Refs.Create (Q);
if Kind = FIFO_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Fifos.Create_Queue (Name, Props, Context);
elsif Kind = PERSISTENT_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Persistents.Create_Queue (Name, Props, Context);
else
raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Kind;
end if;
return Result;
end Create_Queue;
function Null_Queue return Queue_Ref is
Result : Queue_Ref;
begin
return Result;
end Null_Queue;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out Queue_Info) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Queue'Class,
Name => Queue_Access);
begin
if Object.Queue /= null then
Object.Queue.Finalize;
Free (Object.Queue);
end if;
end Finalize;
end AWA.Events.Queues;
|
Fix creation of event queue
|
Fix creation of event queue
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
82c24a070e410bafe77d78e2af313e47de529c1e
|
awa/src/awa-users-modules.adb
|
awa/src/awa-users-modules.adb
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Access);
Plugin.Key_Filter.Initialize (App.all);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Unchecked_Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Unchecked_Access);
Plugin.Key_Filter.Initialize (App.all);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1d7d7515df2d71a1e0565930567b50128392505f
|
ada/reader.adb
|
ada/reader.adb
|
with Ada.IO_Exceptions;
with Ada.Characters.Latin_1;
with Ada.Exceptions;
with Ada.Strings.Maps.Constants;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Smart_Pointers;
with Types.Vector;
with Types.Hash_Map;
package body Reader is
package ACL renames Ada.Characters.Latin_1;
type Lexemes is (Whitespace, Comment,
Int, Float_Tok, Sym,
Nil, True_Tok, False_Tok,
LE_Tok, GE_Tok, Exp_Tok, Splice_Unq,
Str, Atom);
Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set :=
Ada.Strings.Maps.To_Set
(ACL.HT & ACL.LF & ACL.CR & ACL.Space & ACL.Comma);
-- [^\s\[\]{}('"`,;)]
Terminator_Syms : Ada.Strings.Maps.Character_Set :=
Ada.Strings.Maps."or"
(Lisp_Whitespace,
Ada.Strings.Maps.To_Set ("[]{}('""`,;)"));
-- This is raised if an invalid character is encountered
Lexical_Error : exception;
-- The unterminated string error
String_Error : exception;
function Convert_String (S : String) return String is
use Ada.Strings.Unbounded;
Res : Unbounded_String;
I : Positive;
Str_Last : Natural;
begin
Str_Last := S'Last;
I := S'First;
while I <= Str_Last loop
if S (I) = '\' then
if I+1 > Str_Last then
Append (Res, S (I));
I := I + 1;
elsif S (I+1) = 'n' then
Append (Res, Ada.Characters.Latin_1.LF);
I := I + 2;
elsif S (I+1) = '"' then
Append (Res, S (I+1));
I := I + 2;
elsif S (I+1) = '\' then
Append (Res, S (I+1));
I := I + 2;
else
Append (Res, S (I));
I := I + 1;
end if;
else
Append (Res, S (I));
I := I + 1;
end if;
end loop;
return To_String (Res);
end Convert_String;
subtype String_Indices is Integer range 0 .. Max_Line_Len;
Str_Len : String_Indices := 0;
Saved_Line : String (1..Max_Line_Len);
Char_To_Read : String_Indices := 1;
function Get_Token return Types.Mal_Handle is
use Types;
Res : Types.Mal_Handle;
I, J : String_Indices;
Dots : Natural;
All_Digits : Boolean;
begin
<<Tail_Call_Opt>>
I := Char_To_Read;
while I <= Str_Len and then
Ada.Strings.Maps.Is_In (Saved_Line (I), Lisp_Whitespace) loop
I := I + 1;
end loop;
-- Filter out lines consisting of only whitespace
if I > Str_Len then
return Smart_Pointers.Null_Smart_Pointer;
end if;
J := I;
case Saved_Line (J) is
when '~' => -- Circumflex
if J+1 <= Str_Len and then Saved_Line(J+1) = '@' then
Res := New_Unitary_Mal_Type
(Func => Splice_Unquote,
Op => Smart_Pointers.Null_Smart_Pointer);
Char_To_Read := J+2;
else
-- Just a circumflex
Res := New_Atom_Mal_Type (Saved_Line (J..J));
Char_To_Read := J+1;
end if;
when '[' | ']' |
'{' | '}' |
'(' | ')' |
''' | '`' |
'^' | '@' =>
Res := New_Atom_Mal_Type (Saved_Line (J..J));
Char_To_Read := J+1;
when '"' => -- a string
-- Skip over "
J := J + 1;
while J <= Str_Len and then
(Saved_Line (J) /= '"' or else
Saved_Line (J-1) = '\') loop
J := J + 1;
end loop;
-- So we either ran out of string..
if J > Str_Len then
raise String_Error;
end if;
-- or we reached an unescaped "
Res := New_String_Mal_Type
(Str => Convert_String (Saved_Line (I .. J)));
Char_To_Read := J + 1;
when ';' => -- a comment
-- Read to the end of the line or until
-- the saved_line string is exhausted.
-- NB if we reach the end we don't care
-- what the last char was.
while J < Str_Len and Saved_Line (J) /= ACL.LF loop
J := J + 1;
end loop;
if J = Str_Len then
Res := Smart_Pointers.Null_Smart_Pointer;
else
Char_To_Read := J + 1;
-- was: Res := Get_Token;
goto Tail_Call_Opt;
end if;
when others => -- an atom
while J <= Str_Len and then
not Ada.Strings.Maps.Is_In (Saved_Line (J), Terminator_Syms) loop
J := J + 1;
end loop;
-- Either we ran out of string or
-- the one at J was the start of a new token
Char_To_Read := J;
J := J - 1;
-- check if all digits or .
Dots := 0;
All_Digits := True;
for K in I .. J loop
if Saved_Line (K) = '.' then
Dots := Dots + 1;
elsif not (Saved_Line (K) in '0' .. '9') then
All_Digits := False;
exit;
end if;
end loop;
if All_Digits then
if Dots = 0 then
Res := New_Int_Mal_Type
(Int => Mal_Integer'Value (Saved_Line (I .. J)));
elsif Dots = 1 then
Res := New_Float_Mal_Type
(Floating => Mal_Float'Value (Saved_Line (I..J)));
else
Res := New_Atom_Mal_Type (Saved_Line (I..J));
end if;
else
Res := New_Atom_Mal_Type (Saved_Line (I..J));
end if;
end case;
return Res;
end Get_Token;
-- Parsing
function Read_Form return Types.Mal_Handle;
function Read_List (LT : Types.List_Types)
return Types.Mal_Handle is
use Types;
MTA : Mal_Handle;
begin
MTA := Read_Form;
if Deref (MTA).Sym_Type = Atom and then
Deref_Atom (MTA).Get_Atom = "fn*" then
declare
Params, Expr, Close_Lambda : Mal_Handle;
begin
Params := Read_Form;
Expr := Read_Form;
Close_Lambda := Read_Form; -- the ) at the end of the lambda
return New_Lambda_Mal_Type (Params, Expr);
exception
when Lexical_Error =>
-- List_MT about to go out of scope but its a Mal_Handle
-- so it is automatically garbage collected.
return New_Error_Mal_Type (Str => "Lexical error in fn*");
end;
else
declare
List_SP : Mal_Handle;
List_P : List_Class_Ptr;
Close : String (1..1) := (1 => Types.Closing (LT));
begin
case LT is
when List_List =>
List_SP := New_List_Mal_Type (List_Type => LT);
when Vector_List =>
List_SP := Vector.New_Vector_Mal_Type;
when Hashed_List =>
List_SP := Hash_Map.New_Hash_Map_Mal_Type;
end case;
-- Need to append to a variable so...
List_P := Deref_List_Class (List_SP);
loop
exit when Is_Null (MTA) or else
(Deref (MTA).Sym_Type = Atom and then
Atom_Mal_Type (Deref (MTA).all).Get_Atom = Close);
Append (List_P.all, MTA);
MTA := Read_Form;
end loop;
return List_SP;
exception
when Lexical_Error =>
-- List_MT about to go out of scope but its a Mal_Handle
-- so it is automatically garbage collected.
return New_Error_Mal_Type (Str => "expected '" & Close & "'");
end;
end if;
exception
when Lexical_Error =>
return New_Error_Mal_Type (Str => "Lexical error in Read_List");
end Read_List;
function Read_Form return Types.Mal_Handle is
use Types;
MTS : Mal_Handle;
begin
MTS := Get_Token;
if Is_Null (MTS) then
return Smart_Pointers.Null_Smart_Pointer;
end if;
if Deref (MTS).Sym_Type = Atom then
declare
Symbol : String := Atom_Mal_Type (Deref (MTS).all).Get_Atom;
begin
-- Listy things and quoting...
if Symbol = "(" then
return Read_List (List_List);
elsif Symbol = "[" then
return Read_List (Vector_List);
elsif Symbol = "{" then
return Read_List (Hashed_List);
elsif Symbol = "^" then
declare
Meta, Obj : Mal_Handle;
begin
Meta := Read_Form;
Obj := Read_Form;
declare
MT : Mal_Ptr := Deref (Obj);
begin
Set_Meta (MT.all, Meta);
end;
return Obj;
end;
elsif Symbol = ACL.Apostrophe & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("quote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Grave & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("quasiquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Tilde & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("unquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Commercial_At & "" then
return New_Unitary_Mal_Type (Func => Deref, Op => Read_Form);
else
return MTS;
end if;
end;
elsif Deref(MTS).Sym_Type = Unitary and then
Unitary_Mal_Type (Deref (MTS).all).Get_Func = Splice_Unquote then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("splice-unquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
else
return MTS;
end if;
exception
when String_Error =>
return New_Error_Mal_Type (Str => "expected '""'");
end Read_Form;
procedure Lex_Init (S : String) is
begin
Str_Len := S'Length;
Saved_Line (1..S'Length) := S; -- Needed for error recovery
Char_To_Read := 1;
end Lex_Init;
function Read_Str (S : String) return Types.Mal_Handle is
I, Str_Len : Natural := S'Length;
begin
Lex_Init (S);
return Read_Form;
end Read_Str;
end Reader;
|
with Ada.IO_Exceptions;
with Ada.Characters.Latin_1;
with Ada.Exceptions;
with Ada.Strings.Maps.Constants;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Smart_Pointers;
with Types.Vector;
with Types.Hash_Map;
package body Reader is
use Types;
package ACL renames Ada.Characters.Latin_1;
type Lexemes is (Whitespace, Comment,
Int_Tok, Float_Tok, Sym_Tok,
Nil_Tok, True_Tok, False_Tok,
LE_Tok, GE_Tok, Exp_Tok, Splice_Unq_Tok,
Str_Tok, Atom_Tok);
Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set :=
Ada.Strings.Maps.To_Set
(ACL.HT & ACL.LF & ACL.CR & ACL.Space & ACL.Comma);
-- [^\s\[\]{}('"`,;)]
Terminator_Syms : Ada.Strings.Maps.Character_Set :=
Ada.Strings.Maps."or"
(Lisp_Whitespace,
Ada.Strings.Maps.To_Set ("[]{}('""`,;)"));
-- The unterminated string error
String_Error : exception;
function Convert_String (S : String) return String is
use Ada.Strings.Unbounded;
Res : Unbounded_String;
I : Positive;
Str_Last : Natural;
begin
Str_Last := S'Last;
I := S'First;
while I <= Str_Last loop
if S (I) = '\' then
if I+1 > Str_Last then
Append (Res, S (I));
I := I + 1;
elsif S (I+1) = 'n' then
Append (Res, Ada.Characters.Latin_1.LF);
I := I + 2;
elsif S (I+1) = '"' then
Append (Res, S (I+1));
I := I + 2;
elsif S (I+1) = '\' then
Append (Res, S (I+1));
I := I + 2;
else
Append (Res, S (I));
I := I + 1;
end if;
else
Append (Res, S (I));
I := I + 1;
end if;
end loop;
return To_String (Res);
end Convert_String;
subtype String_Indices is Integer range 0 .. Max_Line_Len;
Str_Len : String_Indices := 0;
Saved_Line : String (1..Max_Line_Len);
Char_To_Read : String_Indices := 1;
function Get_Token return Types.Mal_Handle is
Res : Types.Mal_Handle;
I, J : String_Indices;
Dots : Natural;
All_Digits : Boolean;
begin
<<Tail_Call_Opt>>
I := Char_To_Read;
while I <= Str_Len and then
Ada.Strings.Maps.Is_In (Saved_Line (I), Lisp_Whitespace) loop
I := I + 1;
end loop;
-- Filter out lines consisting of only whitespace
if I > Str_Len then
return Smart_Pointers.Null_Smart_Pointer;
end if;
J := I;
case Saved_Line (J) is
when '~' => -- Circumflex
if J+1 <= Str_Len and then Saved_Line(J+1) = '@' then
Res := New_Unitary_Mal_Type
(Func => Splice_Unquote,
Op => Smart_Pointers.Null_Smart_Pointer);
Char_To_Read := J+2;
else
-- Just a circumflex
Res := New_Atom_Mal_Type (Saved_Line (J..J));
Char_To_Read := J+1;
end if;
when '[' | ']' |
'{' | '}' |
'(' | ')' |
''' | '`' |
'^' | '@' =>
Res := New_Atom_Mal_Type (Saved_Line (J..J));
Char_To_Read := J+1;
when '"' => -- a string
-- Skip over "
J := J + 1;
while J <= Str_Len and then
(Saved_Line (J) /= '"' or else
Saved_Line (J-1) = '\') loop
J := J + 1;
end loop;
-- So we either ran out of string..
if J > Str_Len then
raise String_Error;
end if;
-- or we reached an unescaped "
Res := New_String_Mal_Type
(Str => Convert_String (Saved_Line (I .. J)));
Char_To_Read := J + 1;
when ';' => -- a comment
-- Read to the end of the line or until
-- the saved_line string is exhausted.
-- NB if we reach the end we don't care
-- what the last char was.
while J < Str_Len and Saved_Line (J) /= ACL.LF loop
J := J + 1;
end loop;
if J = Str_Len then
Res := Smart_Pointers.Null_Smart_Pointer;
else
Char_To_Read := J + 1;
-- was: Res := Get_Token;
goto Tail_Call_Opt;
end if;
when others => -- an atom
while J <= Str_Len and then
not Ada.Strings.Maps.Is_In (Saved_Line (J), Terminator_Syms) loop
J := J + 1;
end loop;
-- Either we ran out of string or
-- the one at J was the start of a new token
Char_To_Read := J;
J := J - 1;
-- check if all digits or .
Dots := 0;
All_Digits := True;
for K in I .. J loop
if Saved_Line (K) = '.' then
Dots := Dots + 1;
elsif not (Saved_Line (K) in '0' .. '9') then
All_Digits := False;
exit;
end if;
end loop;
if All_Digits then
if Dots = 0 then
Res := New_Int_Mal_Type
(Int => Mal_Integer'Value (Saved_Line (I .. J)));
elsif Dots = 1 then
Res := New_Float_Mal_Type
(Floating => Mal_Float'Value (Saved_Line (I..J)));
else
Res := New_Atom_Mal_Type (Saved_Line (I..J));
end if;
else
Res := New_Atom_Mal_Type (Saved_Line (I..J));
end if;
end case;
return Res;
end Get_Token;
-- Parsing
function Read_Form return Types.Mal_Handle;
function Read_List (LT : Types.List_Types)
return Types.Mal_Handle is
MTA : Mal_Handle;
begin
MTA := Read_Form;
if Deref (MTA).Sym_Type = Atom and then
Deref_Atom (MTA).Get_Atom = "fn*" then
declare
Params, Expr, Close_Lambda : Mal_Handle;
begin
Params := Read_Form;
Expr := Read_Form;
Close_Lambda := Read_Form; -- the ) at the end of the lambda
return New_Lambda_Mal_Type (Params, Expr);
end;
else
declare
List_SP : Mal_Handle;
List_P : List_Class_Ptr;
Close : String (1..1) := (1 => Types.Closing (LT));
begin
case LT is
when List_List =>
List_SP := New_List_Mal_Type (List_Type => LT);
when Vector_List =>
List_SP := Vector.New_Vector_Mal_Type;
when Hashed_List =>
List_SP := Hash_Map.New_Hash_Map_Mal_Type;
end case;
-- Need to append to a variable so...
List_P := Deref_List_Class (List_SP);
loop
if Is_Null (MTA) then
return New_Error_Mal_Type (Str => "expected '" & Close & "'");
end if;
exit when Deref (MTA).Sym_Type = Atom and then
Atom_Mal_Type (Deref (MTA).all).Get_Atom = Close;
Append (List_P.all, MTA);
MTA := Read_Form;
end loop;
return List_SP;
end;
end if;
end Read_List;
function Read_Form return Types.Mal_Handle is
MTS : Mal_Handle;
begin
MTS := Get_Token;
if Is_Null (MTS) then
return Smart_Pointers.Null_Smart_Pointer;
end if;
if Deref (MTS).Sym_Type = Atom then
declare
Symbol : String := Atom_Mal_Type (Deref (MTS).all).Get_Atom;
begin
-- Listy things and quoting...
if Symbol = "(" then
return Read_List (List_List);
elsif Symbol = "[" then
return Read_List (Vector_List);
elsif Symbol = "{" then
return Read_List (Hashed_List);
elsif Symbol = "^" then
declare
Meta, Obj : Mal_Handle;
begin
Meta := Read_Form;
Obj := Read_Form;
declare
MT : Mal_Ptr := Deref (Obj);
begin
Set_Meta (MT.all, Meta);
end;
return Obj;
end;
elsif Symbol = ACL.Apostrophe & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("quote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Grave & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("quasiquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Tilde & "" then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("unquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
elsif Symbol = ACL.Commercial_At & "" then
return New_Unitary_Mal_Type (Func => Deref, Op => Read_Form);
else
return MTS;
end if;
end;
elsif Deref(MTS).Sym_Type = Unitary and then
Unitary_Mal_Type (Deref (MTS).all).Get_Func = Splice_Unquote then
declare
List_SP : Mal_Handle;
List_P : List_Ptr;
begin
List_SP := New_List_Mal_Type (List_Type => List_List);
List_P := Deref_List (List_SP);
Append (List_P.all, New_Atom_Mal_Type ("splice-unquote"));
Append (List_P.all, Read_Form);
return List_SP;
end;
else
return MTS;
end if;
end Read_Form;
procedure Lex_Init (S : String) is
begin
Str_Len := S'Length;
Saved_Line (1..S'Length) := S;
Char_To_Read := 1;
end Lex_Init;
function Read_Str (S : String) return Types.Mal_Handle is
I, Str_Len : Natural := S'Length;
begin
Lex_Init (S);
return Read_Form;
exception
when String_Error =>
return New_Error_Mal_Type (Str => "expected '""'");
end Read_Str;
end Reader;
|
clean up error handling in reader
|
Ada: clean up error handling in reader
|
Ada
|
mpl-2.0
|
joncol/mal,foresterre/mal,jwalsh/mal,jwalsh/mal,alantsev/mal,SawyerHood/mal,DomBlack/mal,hterkelsen/mal,SawyerHood/mal,mpwillson/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,jwalsh/mal,SawyerHood/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,mpwillson/mal,jwalsh/mal,mpwillson/mal,SawyerHood/mal,alantsev/mal,foresterre/mal,alantsev/mal,0gajun/mal,DomBlack/mal,alantsev/mal,alantsev/mal,jwalsh/mal,alantsev/mal,jwalsh/mal,hterkelsen/mal,SawyerHood/mal,foresterre/mal,joncol/mal,DomBlack/mal,mpwillson/mal,alantsev/mal,jwalsh/mal,foresterre/mal,hterkelsen/mal,DomBlack/mal,foresterre/mal,0gajun/mal,joncol/mal,hterkelsen/mal,0gajun/mal,0gajun/mal,alantsev/mal,mpwillson/mal,foresterre/mal,DomBlack/mal,0gajun/mal,hterkelsen/mal,jwalsh/mal,mpwillson/mal,mpwillson/mal,DomBlack/mal,foresterre/mal,0gajun/mal,jwalsh/mal,0gajun/mal,DomBlack/mal,mpwillson/mal,jwalsh/mal,DomBlack/mal,jwalsh/mal,alantsev/mal,SawyerHood/mal,alantsev/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,SawyerHood/mal,foresterre/mal,hterkelsen/mal,DomBlack/mal,jwalsh/mal,hterkelsen/mal,DomBlack/mal,alantsev/mal,jwalsh/mal,foresterre/mal,SawyerHood/mal,DomBlack/mal,hterkelsen/mal,mpwillson/mal,foresterre/mal,hterkelsen/mal,alantsev/mal,mpwillson/mal,DomBlack/mal,alantsev/mal,DomBlack/mal,DomBlack/mal,0gajun/mal,0gajun/mal,jwalsh/mal,SawyerHood/mal,0gajun/mal,hterkelsen/mal,hterkelsen/mal,SawyerHood/mal,SawyerHood/mal,foresterre/mal,SawyerHood/mal,DomBlack/mal,0gajun/mal,0gajun/mal,alantsev/mal,jwalsh/mal,0gajun/mal,hterkelsen/mal,foresterre/mal,jwalsh/mal,0gajun/mal,jwalsh/mal,hterkelsen/mal,hterkelsen/mal,0gajun/mal,hterkelsen/mal,SawyerHood/mal,hterkelsen/mal,0gajun/mal,hterkelsen/mal,0gajun/mal,foresterre/mal,foresterre/mal,mpwillson/mal,mpwillson/mal,mpwillson/mal,SawyerHood/mal,SawyerHood/mal,DomBlack/mal,DomBlack/mal,hterkelsen/mal,0gajun/mal,SawyerHood/mal,SawyerHood/mal,alantsev/mal,alantsev/mal,mpwillson/mal,alantsev/mal,0gajun/mal,hterkelsen/mal
|
a2a9cdd1d3ae7b1bba981df6001c13525bb4ffc0
|
src/util-encoders-base64.adb
|
src/util-encoders-base64.adb
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in base64adecimal
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Encoders.Base64 is
use Interfaces;
use Ada;
use type Ada.Streams.Stream_Element_Offset;
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
Pos : Streams.Stream_Element_Offset := Into'First;
I : Streams.Stream_Element_Offset := Data'First;
C1, C2 : Unsigned_8;
Alphabet : constant Alphabet_Access := E.Alphabet;
begin
while I <= Data'Last loop
if Pos + 4 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Encode the first byte, add padding if necessary.
C1 := Unsigned_8 (Data (I));
Into (Pos) := Alphabet (Shift_Right (C1, 2));
if I = Data'Last then
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 3, 4));
Into (Pos + 2) := Character'Pos ('=');
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the second byte, add padding if necessary.
C2 := Unsigned_8 (Data (I + 1));
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4));
if I = Data'Last - 1 then
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2));
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the third byte
C1 := Unsigned_8 (Data (I + 2));
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6));
Into (Pos + 3) := Alphabet (C1 and 16#03F#);
Pos := Pos + 4;
I := I + 3;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean) is
begin
if Mode then
E.Alphabet := BASE64_URL_ALPHABET'Access;
else
E.Alphabet := BASE64_ALPHABET'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Encoder return Transformer_Access is
begin
return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access);
end Create_URL_Encoder;
-- ------------------------------
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
use Ada.Streams;
Pos : Streams.Stream_Element_Offset := Into'First;
I : Streams.Stream_Element_Offset := Data'First;
C1, C2 : Streams.Stream_Element;
Val1, Val2 : Unsigned_8;
Values : constant Alphabet_Values_Access := E.Values;
begin
while I <= Data'Last loop
if Pos + 3 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Decode the first two bytes to produce the first output byte
C1 := Data (I);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
C2 := Data (I + 1);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4));
if I + 2 > Data'Last then
Encoded := I + 1;
Last := Pos;
return;
end if;
-- Decode the next byte
C1 := Data (I + 2);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
if C1 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
Encoded := I + 3;
Last := Pos;
return;
end if;
Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2));
if I + 3 > Data'Last then
Encoded := I + 2;
Last := Pos + 1;
return;
end if;
C2 := Data (I + 3);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
if C2 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Encoded := I + 3;
Last := Pos + 1;
return;
end if;
Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2);
Pos := Pos + 3;
I := I + 4;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean) is
begin
if Mode then
E.Values := BASE64_URL_VALUES'Access;
else
E.Values := BASE64_VALUES'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Decoder return Transformer_Access is
begin
return new Decoder '(Values => BASE64_URL_VALUES'Access);
end Create_URL_Decoder;
end Util.Encoders.Base64;
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in base64adecimal
-- 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 Util.Streams;
package body Util.Encoders.Base64 is
use Interfaces;
use Ada;
use type Ada.Streams.Stream_Element_Offset;
-- ------------------------------
-- Encode the 64-bit value to LEB128 and then base64url.
-- ------------------------------
function Encode (Value : in Interfaces.Unsigned_64) return String is
E : Encoder;
Data : Ada.Streams.Stream_Element_Array (1 .. 10);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : String (1 .. 16);
Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length);
for Buf'Address use Result'Address;
pragma Import (Ada, Buf);
begin
-- Encode the integer to LEB128 in the data buffer.
Encode_LEB128 (Into => Data,
Pos => Data'First,
Val => Value,
Last => Last);
-- Encode the data buffer in base64url.
E.Set_URL_Mode (True);
E.Transform (Data => Data (Data'First .. Last),
Into => Buf,
Last => Last,
Encoded => Encoded);
-- Strip the '=' or '==' at end of base64url.
if Result (Positive (Last)) /= '=' then
return Result (Result'First .. Positive (Last));
elsif Result (Positive (Last) - 1) /= '=' then
return Result (Result'First .. Positive (Last) - 1);
else
return Result (Result'First .. Positive (Last) - 2);
end if;
end Encode;
-- ------------------------------
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
-- ------------------------------
function Decode (Value : in String) return Interfaces.Unsigned_64 is
D : Decoder;
Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : Interfaces.Unsigned_64;
End_Pos : constant Ada.Streams.Stream_Element_Offset
:= Value'Length + ((4 - (Value'Length mod 4)) mod 4);
begin
Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value);
-- Set back the '=' for the base64url (pad to multiple of 4.
Buf (Value'Length + 1) := Character'Pos ('=');
Buf (Value'Length + 2) := Character'Pos ('=');
-- Decode using base64url
D.Set_URL_Mode (True);
D.Transform (Data => Buf (Buf'First .. End_Pos),
Into => R,
Last => Last,
Encoded => Encoded);
if Encoded /= End_Pos then
raise Encoding_Error with "Input string is too short";
end if;
-- Decode the LEB128 number.
Decode_LEB128 (From => R (R'First .. Last),
Pos => R'First,
Val => Result,
Last => Encoded);
-- Check that everything was decoded.
if Last + 1 /= Encoded then
raise Encoding_Error with "Input string contains garbage at the end";
end if;
return Result;
end Decode;
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Unsigned_8;
Alphabet : constant Alphabet_Access := E.Alphabet;
begin
while I <= Data'Last loop
if Pos + 4 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Encode the first byte, add padding if necessary.
C1 := Unsigned_8 (Data (I));
Into (Pos) := Alphabet (Shift_Right (C1, 2));
if I = Data'Last then
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 3, 4));
Into (Pos + 2) := Character'Pos ('=');
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the second byte, add padding if necessary.
C2 := Unsigned_8 (Data (I + 1));
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4));
if I = Data'Last - 1 then
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2));
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the third byte
C1 := Unsigned_8 (Data (I + 2));
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6));
Into (Pos + 3) := Alphabet (C1 and 16#03F#);
Pos := Pos + 4;
I := I + 3;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean) is
begin
if Mode then
E.Alphabet := BASE64_URL_ALPHABET'Access;
else
E.Alphabet := BASE64_ALPHABET'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Encoder return Transformer_Access is
begin
return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access);
end Create_URL_Encoder;
-- ------------------------------
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
use Ada.Streams;
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Ada.Streams.Stream_Element;
Val1, Val2 : Unsigned_8;
Values : constant Alphabet_Values_Access := E.Values;
begin
while I <= Data'Last loop
if Pos + 3 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Decode the first two bytes to produce the first output byte
C1 := Data (I);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
C2 := Data (I + 1);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4));
if I + 2 > Data'Last then
Encoded := I + 1;
Last := Pos;
return;
end if;
-- Decode the next byte
C1 := Data (I + 2);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
if C1 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
Encoded := I + 3;
Last := Pos;
return;
end if;
Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2));
if I + 3 > Data'Last then
Encoded := I + 2;
Last := Pos + 1;
return;
end if;
C2 := Data (I + 3);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
if C2 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Encoded := I + 3;
Last := Pos + 1;
return;
end if;
Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2);
Pos := Pos + 3;
I := I + 4;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean) is
begin
if Mode then
E.Values := BASE64_URL_VALUES'Access;
else
E.Values := BASE64_VALUES'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Decoder return Transformer_Access is
begin
return new Decoder '(Values => BASE64_URL_VALUES'Access);
end Create_URL_Decoder;
end Util.Encoders.Base64;
|
Implement the Encode and Decode function to encode in LEB128+base64url an integer
|
Implement the Encode and Decode function to encode in LEB128+base64url an integer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e57cfedb8809df5ee3d4ff7840d6012345ffa16c
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
First := Elements'First;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix dequeue in the Clean_On_Dequeue instantiation mode
|
Fix dequeue in the Clean_On_Dequeue instantiation mode
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
fcc23196214b8377a1c57b746fca62488b49365b
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access
:= new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- util-concurrent-fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access
:= new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
add6f42c96b251241fd421388f1ce3b620984fea
|
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 (1 .. Pos - 1),
Value => To_Object (Value (Pos + 1 .. Value'Last)));
else
App.Set_Global (Name => Value (1 .. Pos - 1),
Value => To_Object(True));
end if;
end;
when others =>
exit;
end case;
end loop;
declare
View_Name : constant String := Get_Argument;
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
-----------------------------------------------------------------------
-- 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;
|
Fix usage of render example
|
Fix usage of render example
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
cf0126ce56e6980ed2abf6199566c23fe2ff3668
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_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.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_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.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Move the question services in the question module (simplify the implementation)
|
Move the question services in the question module (simplify the implementation)
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
03a93c1924427f4553e6d336047f8c5c8d1e304e
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
end AWA.Questions.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (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]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Services.Tests;
|
Add unit tests for the questionVote bean
|
Add unit tests for the questionVote bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
12587e3d3fd1630fd305ede9eafa079fd064e239
|
awa/samples/src/atlas-microblog-modules.adb
|
awa/samples/src/atlas-microblog-modules.adb
|
-----------------------------------------------------------------------
-- atlas-microblog-modules -- Module microblog
-- 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 AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Services.Contexts;
with ADO.Sessions;
with Util.Log.Loggers;
with Atlas.Microblog.Beans;
package body Atlas.Microblog.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Microblog.Module");
package Register is new AWA.Modules.Beans (Module => Microblog_Module,
Module_Access => Microblog_Module_Access);
-- ------------------------------
-- Initialize the microblog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Microblog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the microblog module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "Atlas.Microblog.Beans.Microblog_Bean",
Handler => Atlas.Microblog.Beans.Create_Microblog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "Atlas.Microblog.Beans.List_Bean",
Handler => Atlas.Microblog.Beans.Create_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the microblog module.
-- ------------------------------
function Get_Microblog_Module return Microblog_Module_Access is
function Get is new AWA.Modules.Get (Microblog_Module, Microblog_Module_Access, NAME);
begin
return Get;
end Get_Microblog_Module;
-- ------------------------------
-- Create a post for the microblog.
-- ------------------------------
procedure Create (Plugin : in Microblog_Module;
Post : in out Atlas.Microblog.Models.Mblog_Ref) is
pragma Unreferenced (Plugin);
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Author (Ctx.Get_User);
Post.Save (DB);
Ctx.Commit;
end Create;
end Atlas.Microblog.Modules;
|
-----------------------------------------------------------------------
-- atlas-microblog-modules -- Module microblog
-- 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 AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Services.Contexts;
with ADO.Sessions;
with Util.Log.Loggers;
with Atlas.Microblog.Beans;
package body Atlas.Microblog.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Microblog.Module");
package Register is new AWA.Modules.Beans (Module => Microblog_Module,
Module_Access => Microblog_Module_Access);
-- ------------------------------
-- Initialize the microblog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Microblog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the microblog module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "Atlas.Microblog.Beans.Microblog_Bean",
Handler => Atlas.Microblog.Beans.Create_Microblog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "Atlas.Microblog.Beans.List_Bean",
Handler => Atlas.Microblog.Beans.Create_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the microblog module.
-- ------------------------------
function Get_Microblog_Module return Microblog_Module_Access is
function Get is new AWA.Modules.Get (Microblog_Module, Microblog_Module_Access, NAME);
begin
return Get;
end Get_Microblog_Module;
-- ------------------------------
-- Create a post for the microblog.
-- ------------------------------
procedure Create (Plugin : in Microblog_Module;
Post : in out Atlas.Microblog.Models.Mblog_Ref) is
pragma Unreferenced (Plugin);
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Post.Set_Creation_Date (Ada.Calendar.Clock);
Post.Set_Author (Ctx.Get_User);
Post.Save (DB);
Ctx.Commit;
end Create;
end Atlas.Microblog.Modules;
|
Rename Set_Create_Date into Set_Creation_Date
|
Rename Set_Create_Date into Set_Creation_Date
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
e2a9573007399dfea60c55d81cc72c2357b6dcac
|
src/security-oauth.ads
|
src/security-oauth.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
-- RFC 6749: 4.1.2.1. Error Response
ACCESS_DENIED : aliased constant String := "access_denied";
UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type";
SERVER_ERROR : aliased constant String := "server_error";
TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable";
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Get the application identifier.
function Get_Application_Identifier (App : in Application) return String;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
private
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 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;
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
-- RFC 6749: 4.1.2.1. Error Response
ACCESS_DENIED : aliased constant String := "access_denied";
UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type";
SERVER_ERROR : aliased constant String := "server_error";
TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable";
type Client_Authentication_Type is (AUTH_NONE, AUTH_BASIC);
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Get the application identifier.
function Get_Application_Identifier (App : in Application) return String;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
-- Set the client authentication method used when doing OAuth calls for this application.
-- See RFC 6749, 2.3. Client Authentication
procedure Set_Client_Authentication (App : in out Application;
Method : in Client_Authentication_Type);
private
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
Client_Auth : Client_Authentication_Type := AUTH_NONE;
end record;
end Security.OAuth;
|
Declare Set_Client_Authentication procedure Declare Client_Authentication_Type type
|
Declare Set_Client_Authentication procedure
Declare Client_Authentication_Type type
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
8bb9a424cc28e0699954476c6d2278eb82b0036f
|
symbex-lex.ads
|
symbex-lex.ads
|
with Ada.Strings.Wide_Unbounded;
package Symbex.Lex is
type Lexer_t is private;
--
-- Token type.
--
type Token_Kind_t is
(Token_Quoted_String,
Token_Symbol,
Token_List_Open,
Token_List_Close,
Token_EOF);
type Line_Number_t is new Positive;
type Token_t is record
Is_Valid : Boolean;
Line_Number : Line_Number_t;
Kind : Token_Kind_t;
Text : Ada.Strings.Wide_Unbounded.Unbounded_Wide_String;
end record;
--
-- Token value for incomplete or invalid tokens.
--
Invalid_Token : constant Token_t;
--
-- Lexer status value.
--
type Lexer_Status_t is
(Lexer_OK,
Lexer_Needs_More_Data,
Lexer_Error_Line_Overflow,
Lexer_Error_Out_Of_Memory,
Lexer_Error_Stream_Error,
Lexer_Error_Early_EOF);
--
-- Status values corresponding to error conditions.
--
subtype Lexer_Error_Status_t is Lexer_Status_t
range Lexer_Error_Line_Overflow .. Lexer_Status_t'Last;
--
-- Lexer is initialized?
--
function Initialized
(Lexer : in Lexer_t) return Boolean;
--
-- Initialize lexer state.
--
procedure Initialize_Lexer
(Lexer : out Lexer_t;
Status : out Lexer_Status_t);
-- pragma Postcondition
-- (((Status = Lexer_OK) and Initialized (Lexer)) or
-- ((Status /= Lexer_OK) and not Initialized (Lexer)));
--
-- Return token from Read_Item 'stream'.
--
type Stream_Status_t is
(Stream_OK,
Stream_EOF,
Stream_Error);
generic
with procedure Read_Item
(Item : out Wide_Character;
Status : out Stream_Status_t);
procedure Get_Token
(Lexer : in out Lexer_t;
Token : out Token_t;
Status : out Lexer_Status_t);
-- pragma Precondition (Initialized (Lexer));
-- pragma Postcondition
-- (((Status = Lexer_OK) and (Token /= Invalid_Token)) or
-- ((Status /= Lexer_OK) and (Token = Invalid_Token)));
private
package UBW_Strings renames Ada.Strings.Wide_Unbounded;
--
-- Lexer state machine.
--
type State_Stage_t is
(Inside_String,
Inside_Escape,
Inside_Comment);
type State_t is array (State_Stage_t) of Boolean;
type Input_Buffer_Position_t is (Current, Next);
type Input_Buffer_t is array (Input_Buffer_Position_t) of Wide_Character;
subtype Token_Buffer_t is UBW_Strings.Unbounded_Wide_String;
type Lexer_t is record
Inited : Boolean;
Current_Line : Line_Number_t;
Token_Buffer : Token_Buffer_t;
Input_Buffer : Input_Buffer_t;
State : State_t;
end record;
--
-- Token deferred.
--
Invalid_Token : constant Token_t :=
Token_t'(Is_Valid => False,
Line_Number => Line_Number_t'First,
Text => UBW_Strings.Null_Unbounded_Wide_String,
Kind => Token_Kind_t'First);
--
-- Character class.
--
type Character_Class_t is
(Comment_Delimiter,
Escape_Character,
Line_Break,
List_Close_Delimiter,
List_Open_Delimiter,
Ordinary_Text,
String_Delimiter,
Whitespace);
--
-- Utility subprograms.
--
procedure Set_State
(Lexer : in out Lexer_t;
State : in State_Stage_t);
pragma Precondition (not Lexer.State (State));
pragma Postcondition (Lexer.State (State));
procedure Unset_State
(Lexer : in out Lexer_t;
State : in State_Stage_t);
pragma Precondition (Lexer.State (State));
pragma Postcondition (not Lexer.State (State));
function State_Is_Set
(Lexer : in Lexer_t;
State : in State_Stage_t) return Boolean;
function Token_Is_Nonzero_Length
(Lexer : in Lexer_t) return Boolean;
procedure Complete_Token
(Lexer : in out Lexer_t;
Kind : in Token_Kind_t;
Token : out Token_t);
pragma Precondition (Token_Is_Nonzero_Length (Lexer));
-- pragma Postcondition
-- ((Token /= Invalid_Token) and (not Token_Is_Nonzero_Length (Lexer)));
end Symbex.Lex;
|
with Ada.Strings.Wide_Unbounded;
package Symbex.Lex is
type Lexer_t is private;
--
-- Token type.
--
type Token_Kind_t is
(Token_Quoted_String,
Token_Symbol,
Token_List_Open,
Token_List_Close,
Token_EOF);
type Line_Number_t is new Positive;
type Token_t is record
Is_Valid : Boolean;
Line_Number : Line_Number_t;
Kind : Token_Kind_t;
Text : Ada.Strings.Wide_Unbounded.Unbounded_Wide_String;
end record;
--
-- Token value for incomplete or invalid tokens.
--
Invalid_Token : constant Token_t;
--
-- Lexer status value.
--
type Lexer_Status_t is
(Lexer_OK,
Lexer_Needs_More_Data,
Lexer_Error_Line_Overflow,
Lexer_Error_Out_Of_Memory,
Lexer_Error_Stream_Error,
Lexer_Error_Early_EOF);
--
-- Status values corresponding to error conditions.
--
subtype Lexer_Error_Status_t is Lexer_Status_t
range Lexer_Error_Line_Overflow .. Lexer_Status_t'Last;
--
-- Lexer is initialized?
--
function Initialized
(Lexer : in Lexer_t) return Boolean;
--
-- Initialize lexer state.
--
procedure Initialize_Lexer
(Lexer : out Lexer_t;
Status : out Lexer_Status_t);
-- pragma Postcondition
-- (((Status = Lexer_OK) and Initialized (Lexer)) or
-- ((Status /= Lexer_OK) and not Initialized (Lexer)));
--
-- Return token from Read_Item 'stream'.
--
type Stream_Status_t is
(Stream_OK,
Stream_EOF,
Stream_Error);
generic
with procedure Read_Item
(Item : out Wide_Character;
Status : out Stream_Status_t);
procedure Get_Token
(Lexer : in out Lexer_t;
Token : out Token_t;
Status : out Lexer_Status_t);
-- pragma Precondition (Initialized (Lexer));
-- pragma Postcondition
-- (((Status = Lexer_OK) and (Token /= Invalid_Token)) or
-- ((Status /= Lexer_OK) and (Token = Invalid_Token)));
private
package UBW_Strings renames Ada.Strings.Wide_Unbounded;
--
-- Lexer state machine.
--
type State_Stage_t is
(Inside_String,
Inside_Escape,
Inside_Comment);
type State_t is array (State_Stage_t) of Boolean;
type Input_Buffer_Position_t is (Current, Next);
type Input_Buffer_t is array (Input_Buffer_Position_t) of Wide_Character;
subtype Token_Buffer_t is UBW_Strings.Unbounded_Wide_String;
type Lexer_t is record
Inited : Boolean;
Current_Line : Line_Number_t;
Token_Buffer : Token_Buffer_t;
Input_Buffer : Input_Buffer_t;
State : State_t;
end record;
--
-- Token deferred.
--
Invalid_Token : constant Token_t :=
Token_t'(Is_Valid => False,
Line_Number => Line_Number_t'First,
Text => <>,
Kind => Token_Kind_t'First);
--
-- Character class.
--
type Character_Class_t is
(Comment_Delimiter,
Escape_Character,
Line_Break,
List_Close_Delimiter,
List_Open_Delimiter,
Ordinary_Text,
String_Delimiter,
Whitespace);
--
-- Utility subprograms.
--
procedure Set_State
(Lexer : in out Lexer_t;
State : in State_Stage_t);
pragma Precondition (not Lexer.State (State));
pragma Postcondition (Lexer.State (State));
procedure Unset_State
(Lexer : in out Lexer_t;
State : in State_Stage_t);
pragma Precondition (Lexer.State (State));
pragma Postcondition (not Lexer.State (State));
function State_Is_Set
(Lexer : in Lexer_t;
State : in State_Stage_t) return Boolean;
function Token_Is_Nonzero_Length
(Lexer : in Lexer_t) return Boolean;
procedure Complete_Token
(Lexer : in out Lexer_t;
Kind : in Token_Kind_t;
Token : out Token_t);
pragma Precondition (Token_Is_Nonzero_Length (Lexer));
-- pragma Postcondition
-- ((Token /= Invalid_Token) and (not Token_Is_Nonzero_Length (Lexer)));
end Symbex.Lex;
|
Use <> for init.
|
Use <> for init.
|
Ada
|
isc
|
io7m/coreland-symbex,io7m/coreland-symbex
|
f83f2f7fbe5cf0a76ec44090f1aad93d89951cc4
|
src/ado-audits.ads
|
src/ado-audits.ads
|
-----------------------------------------------------------------------
-- ado-audits -- Auditing support
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ADO.Configs;
with ADO.Objects;
with ADO.Schemas;
with ADO.Sessions;
package ADO.Audits is
subtype Object_Key_Type is ADO.Objects.Object_Key_Type;
subtype Auditable_Class_Mapping is ADO.Schemas.Auditable_Class_Mapping;
subtype Auditable_Class_Mapping_Access is ADO.Schemas.Auditable_Class_Mapping_Access;
subtype Class_Mapping_Access is ADO.Schemas.Class_Mapping_Access;
package UBO renames Util.Beans.Objects;
-- The `Audit_Info` describes a column field that is modified.
type Audit_Info is limited record
Field : ADO.Schemas.Column_Index := 0;
Old_Value : UBO.Object;
New_Value : UBO.Object;
end record;
type Audit_Index is new Positive range 1 .. ADO.Configs.MAX_COLUMNS;
type Audit_Array is array (Audit_Index range <>) of Audit_Info;
-- The `Auditable_Object_Record` is the root type of any auditable database record.
-- It inherit from the `Object_Record` and adds auditing support by defining the
-- database column fields which can be audited. When a field is modified, it holds
-- the audit information that tracks the old and new values.
type Auditable_Object_Record (Key_Type : Object_Key_Type;
Of_Class : Class_Mapping_Access;
With_Audit : Auditable_Class_Mapping_Access) is abstract
new ADO.Objects.Object_Record with private;
-- Release the object.
overriding
procedure Finalize (Object : in out Auditable_Object_Record);
-- Record an audit information for a field.
procedure Audit_Field (Object : in out Auditable_Object_Record;
Field : in ADO.Schemas.Column_Index;
Old_Value : in UBO.Object;
New_Value : in UBO.Object);
-- The `Audit_Manager` is the interface of the audit manager component that is responsible
-- for saving the audit information in the database.
type Audit_Manager is limited interface;
-- Save the audit changes in the database.
procedure Save (Manager : in out Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is abstract;
procedure Save (Session : in out ADO.Sessions.Master_Session'Class;
Object : in out Auditable_Object_Record'Class);
private
type Audit_Array_Access is access all Audit_Array;
type Auditable_Object_Record (Key_Type : Object_Key_Type;
Of_Class : Class_Mapping_Access;
With_Audit : Auditable_Class_Mapping_Access) is abstract
new ADO.Objects.Object_Record (Key_Type => Key_Type, Of_Class => Of_Class) with record
Audits : Audit_Array_Access;
end record;
end ADO.Audits;
|
-----------------------------------------------------------------------
-- ado-audits -- Auditing support
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ADO.Configs;
with ADO.Objects;
with ADO.Schemas;
with ADO.Sessions;
package ADO.Audits is
subtype Object_Key_Type is ADO.Objects.Object_Key_Type;
subtype Auditable_Class_Mapping is ADO.Schemas.Auditable_Class_Mapping;
subtype Auditable_Class_Mapping_Access is ADO.Schemas.Auditable_Class_Mapping_Access;
subtype Class_Mapping_Access is ADO.Schemas.Class_Mapping_Access;
package UBO renames Util.Beans.Objects;
-- The `Audit_Info` describes a column field that is modified.
type Audit_Info is limited record
Field : ADO.Schemas.Column_Index := 0;
Old_Value : UBO.Object;
New_Value : UBO.Object;
end record;
type Audit_Index is new Positive range 1 .. ADO.Configs.MAX_COLUMNS;
type Audit_Array is array (Audit_Index range <>) of Audit_Info;
-- The `Auditable_Object_Record` is the root type of any auditable database record.
-- It inherit from the `Object_Record` and adds auditing support by defining the
-- database column fields which can be audited. When a field is modified, it holds
-- the audit information that tracks the old and new values.
type Auditable_Object_Record (Key_Type : Object_Key_Type;
Of_Class : Class_Mapping_Access;
With_Audit : Auditable_Class_Mapping_Access) is abstract
new ADO.Objects.Object_Record with private;
-- Release the object.
overriding
procedure Finalize (Object : in out Auditable_Object_Record);
-- Record an audit information for a field.
procedure Audit_Field (Object : in out Auditable_Object_Record;
Field : in ADO.Schemas.Column_Index;
Old_Value : in UBO.Object;
New_Value : in UBO.Object);
-- The `Audit_Manager` is the interface of the audit manager component that is responsible
-- for saving the audit information in the database.
type Audit_Manager is limited interface;
type Audit_Manager_Access is access all Audit_Manager'Class;
-- Save the audit changes in the database.
procedure Save (Manager : in out Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is abstract;
procedure Save (Session : in out ADO.Sessions.Master_Session'Class;
Object : in out Auditable_Object_Record'Class);
private
type Audit_Array_Access is access all Audit_Array;
type Auditable_Object_Record (Key_Type : Object_Key_Type;
Of_Class : Class_Mapping_Access;
With_Audit : Auditable_Class_Mapping_Access) is abstract
new ADO.Objects.Object_Record (Key_Type => Key_Type, Of_Class => Of_Class) with record
Audits : Audit_Array_Access;
end record;
end ADO.Audits;
|
Declare Audit_Manager_Access access type
|
Declare Audit_Manager_Access access type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
03463ea8eb22d6ffac73ef24dc220b3d705eea92
|
awa/src/awa-oauth-services.ads
|
awa/src/awa-oauth-services.ads
|
-----------------------------------------------------------------------
-- awa-oauth-services -- OAuth Server Side
-- 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 Security.OAuth.Servers;
package AWA.OAuth.Services is
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with private;
type Auth_Manager_Access is access all Auth_Manager'Class;
private
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with record
N : Natural;
end record;
end AWA.OAuth.Services;
|
-----------------------------------------------------------------------
-- awa-oauth-services -- OAuth Server Side
-- 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 Security.OAuth.Servers;
package AWA.OAuth.Services is
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with private;
type Auth_Manager_Access is access all Auth_Manager'Class;
private
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with record
N : Natural;
end record;
end AWA.OAuth.Services;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e40c21ac1087aa6b822e39575b8a4f831fd01fc7
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
DB_Key.Delete (DB);
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Invitation.Save (DB);
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (String '(Invitation.Get_Email));
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (String '(Invitation.Get_Email));
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (String '(Invitation.Get_Email));
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
DB_Key.Delete (DB);
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Invitation.Save (DB);
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
Invit : AWA.Workspaces.Models.Invitation_Ref;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (String '(Invitation.Get_Email));
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (String '(Invitation.Get_Email));
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (String '(Invitation.Get_Email));
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
-- Check for a previous invitation for the user and delete it.
Query.Clear;
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee.Get_Id);
Query.Add_Param (WS.Get_Id);
Invit.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key);
Key.Delete (DB);
if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then
Invit.Delete (DB);
end if;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
Remove a previous invitation to the same user/workspace pair
|
Remove a previous invitation to the same user/workspace pair
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
62649d1482103c28c4d2ca04c675a7f23eee5f05
|
src/gl/interface/gl-toggles.ads
|
src/gl/interface/gl-toggles.ads
|
--------------------------------------------------------------------------------
-- Copyright (c) 2012, Felix Krause <[email protected]>
--
-- 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.
--------------------------------------------------------------------------------
private with GL.Low_Level;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Point_Smooth, Line_Smooth, Line_Stipple, Polygon_Smooth, Polygon_Stipple,
Cull_Face, Lighting, Color_Material,
Fog, Depth_Test, Stencil_Test, Normalize, Alpha_Test, Dither,
Blend, Index_Logic_Op, Color_Logic_Op, Scissor_Test, Texture_Gen_S,
Texture_Gen_T, Texture_Gen_R, Texture_Gen_Q,
Auto_Normal,
Map1_Color_4, Map1_Index,
Map1_Normal, Map1_Texture_Coord_1, Map1_Texture_Coord_2,
Map1_Texture_Coord_3, Map1_Texture_Coord_4,
Map1_Vertex_3, Map1_Vertex_4, Map2_Color_4, Map2_Index,
Map2_Normal, Map2_Texture_Coord_1, Map2_Texture_Coord_2,
Map2_Texture_Coord_3, Map2_Texture_Coord_4, Map2_Vertex_3,
Map2_Vertex_4, Texture_1D, Texture_2D, Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Plane_0, Clip_Plane_1,
Clip_Plane_2, Clip_Plane_3, Clip_Plane_4, Clip_Plane_5,
Light0, Light1, Light2, Light3, Light4, Light5, Light6, Light7,
Convolution_1D, Convolution_2D, Separable_2D, Histogram,
Minmax, Polygon_Offset_Fill, Rescale_Normal, Texture_3D, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One,
Sample_Coverage, Color_Table, Post_Convolution_Color_Table,
Post_Color_Matrix_Color_Table, Color_Sum, Texture_Cube_Map,
Vertex_Program_Point_Size, Vertex_Program_Two_Side, Point_Sprite,
Rasterizer_Discard);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
private
for Toggle use (Point_Smooth => 16#0B10#,
Line_Smooth => 16#0B20#,
Line_Stipple => 16#0B24#,
Polygon_Smooth => 16#0B41#,
Polygon_Stipple => 16#0B42#,
Cull_Face => 16#0B44#,
Lighting => 16#0B50#,
Color_Material => 16#0B57#,
Fog => 16#0B60#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Normalize => 16#0BA1#,
Alpha_Test => 16#0BC0#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Index_Logic_Op => 16#0BF1#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Texture_Gen_S => 16#0C60#,
Texture_Gen_T => 16#0C61#,
Texture_Gen_R => 16#0C62#,
Texture_Gen_Q => 16#0C63#,
Auto_Normal => 16#0D80#,
Map1_Color_4 => 16#0D90#,
Map1_Index => 16#0D91#,
Map1_Normal => 16#0D92#,
Map1_Texture_Coord_1 => 16#0D93#,
Map1_Texture_Coord_2 => 16#0D94#,
Map1_Texture_Coord_3 => 16#0D95#,
Map1_Texture_Coord_4 => 16#0D96#,
Map1_Vertex_3 => 16#0D97#,
Map1_Vertex_4 => 16#0D98#,
Map2_Color_4 => 16#0DB0#,
Map2_Index => 16#0DB1#,
Map2_Normal => 16#0DB2#,
Map2_Texture_Coord_1 => 16#0DB3#,
Map2_Texture_Coord_2 => 16#0DB4#,
Map2_Texture_Coord_3 => 16#0DB5#,
Map2_Texture_Coord_4 => 16#0DB6#,
Map2_Vertex_3 => 16#0DB7#,
Map2_Vertex_4 => 16#0DB8#,
Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Plane_0 => 16#3000#,
Clip_Plane_1 => 16#3001#,
Clip_Plane_2 => 16#3002#,
Clip_Plane_3 => 16#3003#,
Clip_Plane_4 => 16#3004#,
Clip_Plane_5 => 16#3005#,
Light0 => 16#4000#,
Light1 => 16#4001#,
Light2 => 16#4002#,
Light3 => 16#4003#,
Light4 => 16#4004#,
Light5 => 16#4005#,
Light6 => 16#4006#,
Light7 => 16#4007#,
Convolution_1D => 16#8010#,
Convolution_2D => 16#8011#,
Separable_2D => 16#8012#,
Histogram => 16#8024#,
Minmax => 16#802E#,
Polygon_Offset_Fill => 16#8037#,
Rescale_Normal => 16#803A#,
Texture_3D => 16#806F#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Color_Table => 16#80D0#,
Post_Convolution_Color_Table => 16#80D1#,
Post_Color_Matrix_Color_Table => 16#80D2#,
Color_Sum => 16#8458#,
Texture_Cube_Map => 16#8513#,
Vertex_Program_Point_Size => 16#8642#,
Vertex_Program_Two_Side => 16#8643#,
Point_Sprite => 16#8861#,
Rasterizer_Discard => 16#8C89#);
for Toggle'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2012, Felix Krause <[email protected]>
--
-- 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.
--------------------------------------------------------------------------------
private with GL.Low_Level;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Point_Smooth, Line_Smooth, Line_Stipple, Polygon_Smooth, Polygon_Stipple,
Cull_Face, Lighting, Color_Material,
Fog, Depth_Test, Stencil_Test, Normalize, Alpha_Test, Dither,
Blend, Index_Logic_Op, Color_Logic_Op, Scissor_Test, Texture_Gen_S,
Texture_Gen_T, Texture_Gen_R, Texture_Gen_Q,
Auto_Normal,
Map1_Color_4, Map1_Index,
Map1_Normal, Map1_Texture_Coord_1, Map1_Texture_Coord_2,
Map1_Texture_Coord_3, Map1_Texture_Coord_4,
Map1_Vertex_3, Map1_Vertex_4, Map2_Color_4, Map2_Index,
Map2_Normal, Map2_Texture_Coord_1, Map2_Texture_Coord_2,
Map2_Texture_Coord_3, Map2_Texture_Coord_4, Map2_Vertex_3,
Map2_Vertex_4, Texture_1D, Texture_2D, Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Plane_0, Clip_Plane_1,
Clip_Plane_2, Clip_Plane_3, Clip_Plane_4, Clip_Plane_5,
Light0, Light1, Light2, Light3, Light4, Light5, Light6, Light7,
Convolution_1D, Convolution_2D, Separable_2D, Histogram,
Minmax, Polygon_Offset_Fill, Rescale_Normal, Texture_3D, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One,
Sample_Coverage, Color_Table, Post_Convolution_Color_Table,
Post_Color_Matrix_Color_Table, Color_Sum, Texture_Cube_Map,
Vertex_Program_Point_Size, Vertex_Program_Two_Side,
Texture_Cube_Map_Seamless, Point_Sprite, Rasterizer_Discard);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
private
for Toggle use (Point_Smooth => 16#0B10#,
Line_Smooth => 16#0B20#,
Line_Stipple => 16#0B24#,
Polygon_Smooth => 16#0B41#,
Polygon_Stipple => 16#0B42#,
Cull_Face => 16#0B44#,
Lighting => 16#0B50#,
Color_Material => 16#0B57#,
Fog => 16#0B60#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Normalize => 16#0BA1#,
Alpha_Test => 16#0BC0#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Index_Logic_Op => 16#0BF1#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Texture_Gen_S => 16#0C60#,
Texture_Gen_T => 16#0C61#,
Texture_Gen_R => 16#0C62#,
Texture_Gen_Q => 16#0C63#,
Auto_Normal => 16#0D80#,
Map1_Color_4 => 16#0D90#,
Map1_Index => 16#0D91#,
Map1_Normal => 16#0D92#,
Map1_Texture_Coord_1 => 16#0D93#,
Map1_Texture_Coord_2 => 16#0D94#,
Map1_Texture_Coord_3 => 16#0D95#,
Map1_Texture_Coord_4 => 16#0D96#,
Map1_Vertex_3 => 16#0D97#,
Map1_Vertex_4 => 16#0D98#,
Map2_Color_4 => 16#0DB0#,
Map2_Index => 16#0DB1#,
Map2_Normal => 16#0DB2#,
Map2_Texture_Coord_1 => 16#0DB3#,
Map2_Texture_Coord_2 => 16#0DB4#,
Map2_Texture_Coord_3 => 16#0DB5#,
Map2_Texture_Coord_4 => 16#0DB6#,
Map2_Vertex_3 => 16#0DB7#,
Map2_Vertex_4 => 16#0DB8#,
Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Plane_0 => 16#3000#,
Clip_Plane_1 => 16#3001#,
Clip_Plane_2 => 16#3002#,
Clip_Plane_3 => 16#3003#,
Clip_Plane_4 => 16#3004#,
Clip_Plane_5 => 16#3005#,
Light0 => 16#4000#,
Light1 => 16#4001#,
Light2 => 16#4002#,
Light3 => 16#4003#,
Light4 => 16#4004#,
Light5 => 16#4005#,
Light6 => 16#4006#,
Light7 => 16#4007#,
Convolution_1D => 16#8010#,
Convolution_2D => 16#8011#,
Separable_2D => 16#8012#,
Histogram => 16#8024#,
Minmax => 16#802E#,
Polygon_Offset_Fill => 16#8037#,
Rescale_Normal => 16#803A#,
Texture_3D => 16#806F#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Color_Table => 16#80D0#,
Post_Convolution_Color_Table => 16#80D1#,
Post_Color_Matrix_Color_Table => 16#80D2#,
Color_Sum => 16#8458#,
Texture_Cube_Map => 16#8513#,
Vertex_Program_Point_Size => 16#8642#,
Vertex_Program_Two_Side => 16#8643#,
Texture_Cube_Map_Seamless => 16#884F#,
Point_Sprite => 16#8861#,
Rasterizer_Discard => 16#8C89#);
for Toggle'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
Add seamless cube map filtering
|
gl: Add seamless cube map filtering
* Extension ARB_seamless_cube_map (OpenGL 3.2)
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
f237092e278d05429f0a4e839e9628c2622aa133
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : constant Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager;
Name : in String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager;
Name : in String) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Refactor the Properties implementation (step 3): - Update the bundles implementation
|
Refactor the Properties implementation (step 3):
- Update the bundles implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8d244872bf35409ef1de89c167578e9842580e3b
|
awa/src/awa-events-queues-persistents.adb
|
awa/src/awa-events-queues-persistents.adb
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC renames AWA.Services.Contexts;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Event.Get_Event_Kind);
end Set_Event;
begin
App.Do_Event_Manager (Set_Event'Access);
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
-- Collect the event parameters in a string and format the result in JSON.
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props));
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name));
Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props);
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", E, True);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
Log.Info ("Dispatching {0} events", Natural'Image (Count));
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC renames AWA.Services.Contexts;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Event.Get_Event_Kind);
end Set_Event;
begin
App.Do_Event_Manager (Set_Event'Access);
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
Msg.Set_Entity_Id (Event.Get_Entity_Identifier);
Msg.Set_Entity_Type (Event.Entity_Type);
-- Collect the event parameters in a string and format the result in JSON.
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props));
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name));
Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props);
Event.Set_Entity_Identifier (Msg.Get_Entity_Id);
Event.Entity_Type := Msg.Get_Entity_Type;
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", E, True);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
Log.Info ("Dispatching {0} events", Natural'Image (Count));
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
Save and restore the entity identifier associated with an event
|
Save and restore the entity identifier associated with an event
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ca0264590618dc91426bd2b1f01bae98810e075d
|
src/natools-s_expressions-atom_buffers.ads
|
src/natools-s_expressions-atom_buffers.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expressions.Atom_Buffers implements an unbounded Atom designed --
-- to be used as an input buffer, accumulating data and extracting it as a --
-- single Atom object. --
-- It also provides an individual Octet accessor, used in parser internal --
-- recursive buffer. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Refs;
package Natools.S_Expressions.Atom_Buffers is
pragma Preelaborate (Atom_Buffers);
type Atom_Buffer is tagged private;
pragma Preelaborable_Initialization (Atom_Buffer);
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count);
-- Preallocate enough memory to append Length octets without
-- any further allocation.
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom);
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet);
-- Append Data after the end of Buffer
procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom);
-- Append bytes from Atom from last to first
procedure Invert (Buffer : in out Atom_Buffer);
-- Invert the order of bytes (first becomes last, etc)
function Length (Buffer : Atom_Buffer) return Count;
function Capacity (Buffer : Atom_Buffer) return Count;
function Data (Buffer : Atom_Buffer) return Atom;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom));
procedure Read
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count);
function Element (Buffer : Atom_Buffer; Position : Count) return Octet;
-- Accessors to the whole buffer as an Atom
procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet);
-- Remove last octet from Buffer and store it in Data
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor;
-- Accessor to the whole allocated memory
procedure Hard_Reset (Buffer : in out Atom_Buffer);
-- Clear buffer and release internal memory
procedure Soft_Reset (Buffer : in out Atom_Buffer);
-- Clear buffer keeping internal memory
private
type Atom_Buffer is tagged record
Ref : Atom_Refs.Reference;
Available, Used : Count := 0;
end record;
end Natools.S_Expressions.Atom_Buffers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expressions.Atom_Buffers implements an unbounded Atom designed --
-- to be used as an input buffer, accumulating data and extracting it as a --
-- single Atom object. --
-- It also provides an individual Octet accessor, used in parser internal --
-- recursive buffer. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Refs;
package Natools.S_Expressions.Atom_Buffers is
pragma Preelaborate (Atom_Buffers);
type Atom_Buffer is tagged limited private;
pragma Preelaborable_Initialization (Atom_Buffer);
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count);
-- Preallocate enough memory to append Length octets without
-- any further allocation.
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom);
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet);
-- Append Data after the end of Buffer
procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom);
-- Append bytes from Atom from last to first
procedure Invert (Buffer : in out Atom_Buffer);
-- Invert the order of bytes (first becomes last, etc)
function Length (Buffer : Atom_Buffer) return Count;
function Capacity (Buffer : Atom_Buffer) return Count;
function Data (Buffer : Atom_Buffer) return Atom;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom));
procedure Read
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count);
function Element (Buffer : Atom_Buffer; Position : Count) return Octet;
-- Accessors to the whole buffer as an Atom
procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet);
-- Remove last octet from Buffer and store it in Data
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor;
-- Accessor to the whole allocated memory
procedure Hard_Reset (Buffer : in out Atom_Buffer);
-- Clear buffer and release internal memory
procedure Soft_Reset (Buffer : in out Atom_Buffer);
-- Clear buffer keeping internal memory
private
type Atom_Buffer is tagged limited record
Ref : Atom_Refs.Reference;
Available, Used : Count := 0;
end record;
end Natools.S_Expressions.Atom_Buffers;
|
make Atom_Buffer type limited, since copying such objects would cause complex and useless consequences
|
s_expressions-atom_buffers: make Atom_Buffer type limited, since copying such objects would cause complex and useless consequences
|
Ada
|
isc
|
faelys/natools
|
a7897682493d9fd7bddbe2ad3502c9bc23a4d92e
|
src/asf-components-utils.adb
|
src/asf-components-utils.adb
|
-----------------------------------------------------------------------
-- components-util -- ASF Util Components
-- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Views;
with ASF.Views.Nodes;
package body ASF.Components.Utils is
function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info;
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is
Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag;
begin
if Tag /= null then
return Tag.Get_Line_Info;
else
return Tag.Get_Line_Info;
end if;
end Get_Line_Info;
pragma Unreferenced (Get_Line_Info);
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in Base.UIComponent'Class) return String is
Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag;
begin
if Tag /= null then
return Tag.Get_Line_Info;
else
return "?";
end if;
end Get_Line_Info;
-- ------------------------------
-- Get the component attribute that implements the <tt>List_Bean</tt> interface.
-- Returns null if the attribute is not found or does not implement the interface.
-- ------------------------------
function Get_List_Bean (UI : in Base.UIComponent'Class;
Name : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Beans.Basic.List_Bean_Access is
use type Util.Beans.Objects.Data_Type;
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, Name);
Kind : constant Util.Beans.Objects.Data_Type := Util.Beans.Objects.Get_Type (Value);
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
List : Util.Beans.Basic.List_Bean_Access;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= Util.Beans.Objects.TYPE_BEAN then
if Kind /= Util.Beans.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
Util.Beans.Objects.Get_Type_Name (Value));
end if;
return null;
end if;
Bean := Util.Beans.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: it does not implement"
&" 'List_Bean' interface");
return null;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
return List;
end Get_List_Bean;
end ASF.Components.Utils;
|
-----------------------------------------------------------------------
-- components-util -- ASF Util Components
-- Copyright (C) 2009, 2010, 2011, 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.Beans.Objects;
with ASF.Views;
with ASF.Views.Nodes;
package body ASF.Components.Utils is
function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info;
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is
Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag;
begin
if Tag /= null then
return Tag.Get_Line_Info;
else
return Tag.Get_Line_Info;
end if;
end Get_Line_Info;
pragma Unreferenced (Get_Line_Info);
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in Base.UIComponent'Class) return String is
Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag;
begin
if Tag /= null then
return Tag.Get_Line_Info;
else
return "?";
end if;
end Get_Line_Info;
-- ------------------------------
-- Get the component attribute that implements the <tt>List_Bean</tt> interface.
-- Returns null if the attribute is not found or does not implement the interface.
-- ------------------------------
function Get_List_Bean (UI : in Base.UIComponent'Class;
Name : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Beans.Basic.List_Bean_Access is
use type Util.Beans.Objects.Data_Type;
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, Name);
Kind : constant Util.Beans.Objects.Data_Type := Util.Beans.Objects.Get_Type (Value);
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
List : Util.Beans.Basic.List_Bean_Access;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= Util.Beans.Objects.TYPE_BEAN then
if Kind /= Util.Beans.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
Util.Beans.Objects.Get_Type_Name (Value));
end if;
return null;
end if;
Bean := Util.Beans.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: it does not implement"
& " 'List_Bean' interface");
return null;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
return List;
end Get_List_Bean;
end ASF.Components.Utils;
|
Fix style compilation warning
|
Fix style compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
d7dd4ff082d113ea5151c3c5fe1cfa6e8e07cc67
|
src/gen-artifacts-docs-markdown.adb
|
src/gen-artifacts-docs-markdown.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Artifacts.Docs.Markdown is
use type Ada.Strings.Maps.Character_Set;
function Has_Scheme (Link : in String) return Boolean;
function Is_Image (Link : in String) return Boolean;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark");
Marker : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" .,;:!?")
or Ada.Strings.Maps.To_Set (ASCII.HT)
or Ada.Strings.Maps.To_Set (ASCII.VT)
or Ada.Strings.Maps.To_Set (ASCII.CR)
or Ada.Strings.Maps.To_Set (ASCII.LF);
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
pragma Unreferenced (Formatter);
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
pragma Unreferenced (Formatter);
begin
if Document.Print_Footer then
Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end if;
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
function Is_Image (Link : in String) return Boolean is
begin
if Link'Length < 4 then
return False;
elsif Link (Link'Last - 3 .. Link'Last) = ".png" then
return True;
elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then
return True;
elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then
return True;
else
Log.Info ("Link {0} not an image", Link);
return False;
end if;
end Is_Image;
procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Start : Natural := Text'First;
Last : Natural := Text'Last;
Link : Util.Strings.Maps.Cursor;
Pos : Natural;
begin
Log.Debug ("Auto link |{0}|", Text);
loop
-- Emit spaces at beginning of line or words.
while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop
Ada.Text_IO.Put (File, Text (Start));
Start := Start + 1;
end loop;
exit when Start > Text'Last;
-- Find a possible link.
Link := Formatter.Links.Find (Text (Start .. Last));
if Util.Strings.Maps.Has_Element (Link) then
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (Start .. Last));
Ada.Text_IO.Put (File, "](");
Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link));
Ada.Text_IO.Put (File, ")");
Start := Last + 1;
Last := Text'Last;
else
Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker,
Going => Ada.Strings.Backward);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Last));
Start := Last + 1;
Last := Text'Last;
else
Last := Pos - 1;
-- Skip spaces at end of words for the search.
while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop
Last := Last - 1;
end loop;
end if;
end if;
end loop;
end Write_Text_Auto_Links;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
-- Transform links
-- [Link] -> [[Link]]
-- [Link Title] -> [[Title|Link]]
--
-- Do not change the following links:
-- [[Link|Title]]
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last));
return;
end if;
Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1));
if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then
Ada.Text_IO.Put (File, "[");
Start := Pos + 1;
-- Parse a markdown link format.
elsif Text (Pos + 1) = '[' then
Start := Pos + 2;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
if Is_Image (Text (Start .. Text'Last)) then
Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last));
else
Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last));
end if;
return;
end if;
if Is_Image (Text (Start .. Pos - 1)) then
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Start .. Pos - 1));
Ada.Text_IO.Put (File, ")");
Start := Pos + 2;
else
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
end if;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Is_Image (Text (Pos .. Last_Pos - 1)) then
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1));
Ada.Text_IO.Put (File, ")");
elsif Is_Image (Text (Pos .. End_Pos)) then
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
elsif Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File,
Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- Write a line in the document.
-- ------------------------------
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String) is
begin
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
end Write_Line;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
case Line.Kind is
when L_LIST =>
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```Ada");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "#### " & Line.Content);
Formatter.Mode := L_TEXT;
when others =>
null;
end case;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
pragma Unreferenced (Formatter);
begin
Ada.Text_IO.New_Line (File);
if Document.Print_Footer then
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end if;
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Artifacts.Docs.Markdown is
use type Ada.Strings.Maps.Character_Set;
function Has_Scheme (Link : in String) return Boolean;
function Is_Image (Link : in String) return Boolean;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark");
Marker : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" .,;:!?")
or Ada.Strings.Maps.To_Set (ASCII.HT)
or Ada.Strings.Maps.To_Set (ASCII.VT)
or Ada.Strings.Maps.To_Set (ASCII.CR)
or Ada.Strings.Maps.To_Set (ASCII.LF);
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
pragma Unreferenced (Formatter);
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
pragma Unreferenced (Formatter);
begin
if Document.Print_Footer then
Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end if;
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
function Is_Image (Link : in String) return Boolean is
begin
if Link'Length < 4 then
return False;
elsif Link (Link'Last - 3 .. Link'Last) = ".png" then
return True;
elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then
return True;
elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then
return True;
else
Log.Info ("Link {0} not an image", Link);
return False;
end if;
end Is_Image;
procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Start : Natural := Text'First;
Last : Natural := Text'Last;
Link : Util.Strings.Maps.Cursor;
Pos : Natural;
begin
Log.Debug ("Auto link |{0}|", Text);
loop
-- Emit spaces at beginning of line or words.
while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop
Ada.Text_IO.Put (File, Text (Start));
Start := Start + 1;
end loop;
exit when Start > Text'Last;
-- Find a possible link.
Link := Formatter.Links.Find (Text (Start .. Last));
if Util.Strings.Maps.Has_Element (Link) then
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (Start .. Last));
Ada.Text_IO.Put (File, "](");
Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link));
Ada.Text_IO.Put (File, ")");
Start := Last + 1;
Last := Text'Last;
else
Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker,
Going => Ada.Strings.Backward);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Last));
Start := Last + 1;
Last := Text'Last;
else
Last := Pos - 1;
-- Skip spaces at end of words for the search.
while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop
Last := Last - 1;
end loop;
end if;
end if;
end loop;
end Write_Text_Auto_Links;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
-- Transform links
-- [Link] -> [[Link]]
-- [Link Title] -> [[Title|Link]]
--
-- Do not change the following links:
-- [[Link|Title]]
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last));
return;
end if;
Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1));
if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then
Ada.Text_IO.Put (File, "[");
Start := Pos + 1;
-- Parse a markdown link format.
elsif Text (Pos + 1) = '[' then
Start := Pos + 2;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
if Is_Image (Text (Start .. Text'Last)) then
Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last));
else
Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last));
end if;
return;
end if;
if Is_Image (Text (Start .. Pos - 1)) then
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Start .. Pos - 1));
Ada.Text_IO.Put (File, ")");
Start := Pos + 2;
else
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
end if;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Is_Image (Text (Pos .. Last_Pos - 1)) then
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1));
Ada.Text_IO.Put (File, ")");
elsif Is_Image (Text (Pos .. End_Pos)) then
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, ";
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
elsif Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File,
Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- Write a line in the document.
-- ------------------------------
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String) is
begin
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
end Write_Line;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
case Line.Kind is
when L_LIST =>
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```Ada");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
if Formatter.Mode /= L_START_CODE then
Formatter.Mode := L_TEXT;
end if;
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "#### " & Line.Content);
Formatter.Mode := L_TEXT;
when others =>
null;
end case;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
pragma Unreferenced (Formatter);
begin
Ada.Text_IO.New_Line (File);
if Document.Print_Footer then
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end if;
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
Fix formatting of code blocks
|
Fix formatting of code blocks
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5d4de6d1a42b3873256670c42e945f5bf055a2fd
|
src/gl/interface/gl-toggles.ads
|
src/gl/interface/gl-toggles.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with GL.Low_Level;
with GL.Types;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Line_Smooth, Polygon_Smooth, Cull_Face, Depth_Test,
Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test,
Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3,
Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7,
Polygon_Offset_Fill, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage,
Debug_Output_Synchronous,
Program_Point_Size, Depth_Clamp,
Texture_Cube_Map_Seamless, Sample_Shading,
Rasterizer_Discard, Primitive_Restart_Fixed_Index,
Framebuffer_SRGB, Sample_Mask, Primitive_Restart,
Debug_Output);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
type Toggle_Indexed is (Blend, Scissor_Test);
procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State);
function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State;
private
for Toggle use (Line_Smooth => 16#0B20#,
Polygon_Smooth => 16#0B41#,
Cull_Face => 16#0B44#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Distance_0 => 16#3000#,
Clip_Distance_1 => 16#3001#,
Clip_Distance_2 => 16#3002#,
Clip_Distance_3 => 16#3003#,
Clip_Distance_4 => 16#3004#,
Clip_Distance_5 => 16#3005#,
Clip_Distance_6 => 16#3006#,
Clip_Distance_7 => 16#3007#,
Polygon_Offset_Fill => 16#8037#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Debug_Output_Synchronous => 16#8242#,
Program_Point_Size => 16#8642#,
Depth_Clamp => 16#864F#,
Texture_Cube_Map_Seamless => 16#884F#,
Sample_Shading => 16#8C36#,
Rasterizer_Discard => 16#8C89#,
Primitive_Restart_Fixed_Index => 16#8D69#,
Framebuffer_SRGB => 16#8DB9#,
Sample_Mask => 16#8E51#,
Primitive_Restart => 16#8F9D#,
Debug_Output => 16#92E0#);
for Toggle'Size use Low_Level.Enum'Size;
for Toggle_Indexed use
(Blend => 16#0BE2#,
Scissor_Test => 16#0C11#);
for Toggle_Indexed'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with GL.Low_Level;
with GL.Types;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Cull_Face, Depth_Test,
Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test,
Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3,
Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7,
Polygon_Offset_Fill, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage,
Debug_Output_Synchronous,
Program_Point_Size, Depth_Clamp,
Texture_Cube_Map_Seamless, Sample_Shading,
Rasterizer_Discard, Primitive_Restart_Fixed_Index,
Framebuffer_SRGB, Sample_Mask, Primitive_Restart,
Debug_Output);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
type Toggle_Indexed is (Blend, Scissor_Test);
procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State);
function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State;
private
for Toggle use (Cull_Face => 16#0B44#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Distance_0 => 16#3000#,
Clip_Distance_1 => 16#3001#,
Clip_Distance_2 => 16#3002#,
Clip_Distance_3 => 16#3003#,
Clip_Distance_4 => 16#3004#,
Clip_Distance_5 => 16#3005#,
Clip_Distance_6 => 16#3006#,
Clip_Distance_7 => 16#3007#,
Polygon_Offset_Fill => 16#8037#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Debug_Output_Synchronous => 16#8242#,
Program_Point_Size => 16#8642#,
Depth_Clamp => 16#864F#,
Texture_Cube_Map_Seamless => 16#884F#,
Sample_Shading => 16#8C36#,
Rasterizer_Discard => 16#8C89#,
Primitive_Restart_Fixed_Index => 16#8D69#,
Framebuffer_SRGB => 16#8DB9#,
Sample_Mask => 16#8E51#,
Primitive_Restart => 16#8F9D#,
Debug_Output => 16#92E0#);
for Toggle'Size use Low_Level.Enum'Size;
for Toggle_Indexed use
(Blend => 16#0BE2#,
Scissor_Test => 16#0C11#);
for Toggle_Indexed'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
Remove old toggles to do line/polygon smoothing
|
gl: Remove old toggles to do line/polygon smoothing
Use MSAA and/or post-processing algorithms like FXAA, SMAA, or CMAA.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
8770615bf15b0390877d7f570f7b74a5b6970b50
|
src/atlas-microblog-beans.ads
|
src/atlas-microblog-beans.ads
|
-----------------------------------------------------------------------
-- atlas-microblog-beans -- Beans for module microblog
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Atlas.Microblog.Modules;
with Atlas.Microblog.Models;
package Atlas.Microblog.Beans is
type Microblog_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Module : Atlas.Microblog.Modules.Microblog_Module_Access := null;
Post : Atlas.Microblog.Models.Mblog_Ref;
end record;
type Microblog_Bean_Access is access all Microblog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Microblog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Microblog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Microblog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Post the microblog
procedure Post (Bean : in out Microblog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Microblog_Bean bean instance.
function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the a bean to display the list of microblog posts.
function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end Atlas.Microblog.Beans;
|
-----------------------------------------------------------------------
-- atlas-microblog-beans -- Beans for module microblog
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with AWA.Events;
with Atlas.Microblog.Modules;
with Atlas.Microblog.Models;
package Atlas.Microblog.Beans is
type Microblog_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Module : Atlas.Microblog.Modules.Microblog_Module_Access := null;
Post : Atlas.Microblog.Models.Mblog_Ref;
end record;
type Microblog_Bean_Access is access all Microblog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Microblog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Microblog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Microblog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Post the microblog
procedure Post (Bean : in out Microblog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Post a message when some event is received.
procedure Post (Bean : in out Microblog_Bean;
Event : in AWA.Events.Module_Event'Class);
-- Create the Microblog_Bean bean instance.
function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the a bean to display the list of microblog posts.
function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end Atlas.Microblog.Beans;
|
Declare Post procedure with an event as parameter
|
Declare Post procedure with an event as parameter
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
941988973d01afd3f0149384d33040cfdc4c3bfe
|
src/util-beans-objects-maps.ads
|
src/util-beans-objects-maps.ads
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Beans.Basic;
package Util.Beans.Objects.Maps is
package Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Object,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Cursor is Maps.Cursor;
subtype Map is Maps.Map;
-- Make all the Maps operations available (a kind of 'use Maps' for anybody).
function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length;
function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty;
procedure Clear (Container : in out Map) renames Maps.Clear;
function Key (Position : Cursor) return String renames Maps.Key;
procedure Include (Container : in out Map;
Key : in String;
New_Item : in Object) renames Maps.Include;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Key : String;
Element : Object))
renames Maps.Query_Element;
function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element;
function Element (Position : Cursor) return Object renames Maps.Element;
procedure Next (Position : in out Cursor) renames Maps.Next;
function Next (Position : Cursor) return Cursor renames Maps.Next;
function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : String) return Boolean
renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : String; Right : Cursor) return Boolean
renames Maps.Equivalent_Keys;
function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map
renames Maps.Copy;
-- ------------------------------
-- 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 Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private;
type Map_Bean_Access is access all Map_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 Map_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 Map_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Map_Bean</tt> instance.
function Create return Object;
-- Iterate over the members of the map.
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object));
private
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Maps;
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Beans.Basic;
package Util.Beans.Objects.Maps is
package Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Object,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Cursor is Maps.Cursor;
subtype Map is Maps.Map;
-- Make all the Maps operations available (a kind of 'use Maps' for anybody).
function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length;
function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty;
procedure Clear (Container : in out Map) renames Maps.Clear;
function Key (Position : Cursor) return String renames Maps.Key;
procedure Include (Container : in out Map;
Key : in String;
New_Item : in Object) renames Maps.Include;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Key : String;
Element : Object))
renames Maps.Query_Element;
function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element;
function Element (Position : Cursor) return Object renames Maps.Element;
procedure Next (Position : in out Cursor) renames Maps.Next;
function Next (Position : Cursor) return Cursor renames Maps.Next;
function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : String) return Boolean
renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : String; Right : Cursor) return Boolean
renames Maps.Equivalent_Keys;
function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map
renames Maps.Copy;
-- ------------------------------
-- 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 Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private;
type Map_Bean_Access is access all Map_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 Map_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 Map_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Map_Bean</tt> instance.
function Create return Object;
-- Iterate over the members of the map.
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object));
private
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Maps;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1fd9167c890b199afc8fe649a0ce2e6f5242a314
|
src/wiki-filters-collectors.adb
|
src/wiki-filters-collectors.adb
|
-----------------------------------------------------------------------
-- wiki-filters-collectors -- Wiki word and link collectors
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Collectors is
procedure Add_String (Into : in out WString_Maps.Map;
Item : in Wiki.Strings.WString);
procedure Add_String (Into : in out WString_Maps.Map;
Item : in Wiki.Strings.WString) is
procedure Increment (Key : in Wiki.Strings.WString;
Value : in out Natural);
procedure Increment (Key : in Wiki.Strings.WString;
Value : in out Natural) is
pragma Unreferenced (Key);
begin
Value := Value + 1;
end Increment;
Pos : constant WString_Maps.Cursor := Into.Find (Item);
begin
if WString_Maps.Has_Element (Pos) then
Into.Update_Element (Pos, Increment'Access);
else
Into.Insert (Item, 1);
end if;
end Add_String;
function Find (Map : in Collector_Type;
Item : in Wiki.Strings.WString) return Cursor is
begin
return Map.Items.Find (Item);
end Find;
function Contains (Map : in Collector_Type;
Item : in Wiki.Strings.WString) return Boolean is
begin
return Map.Items.Contains (Item);
end Contains;
procedure Iterate (Map : in Collector_Type;
Process : not null access procedure (Pos : in Cursor)) is
begin
Map.Items.Iterate (Process);
end Iterate;
-- ------------------------------
-- Word Collector type
-- ------------------------------
procedure Collect_Words (Filter : in out Word_Collector_Type;
Content : in Wiki.Strings.WString) is
Pos : Natural := Content'First;
Start : Natural := Content'First;
C : Wiki.Strings.WChar;
begin
while Pos <= Content'Last loop
C := Content (Pos);
if Wiki.Strings.Is_Alphanumeric (C) then
null;
else
if Start + 1 < Pos - 1 then
Add_String (Filter.Items, Content (Start .. Pos - 1));
end if;
Start := Pos + 1;
end if;
Pos := Pos + 1;
end loop;
if Start < Content'Last then
Add_String (Filter.Items, Content (Start .. Content'Last));
end if;
end Collect_Words;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
Filter.Collect_Words (Text);
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Collect_Words (Header);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Filter.Collect_Words (Text);
Filter_Type (Filter).Add_Preformatted (Document, Text, Format);
end Add_Preformatted;
procedure Collect_Link (Filter : in out Link_Collector_Type;
Attributes : in Wiki.Attributes.Attribute_List;
Name : in String) is
Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, Name);
begin
if Href'Length > 0 then
Add_String (Filter.Items, Href);
end if;
end Collect_Link;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Link_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Collect_Link (Filter, Attributes, "href");
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end Add_Link;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Link_Collector_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Tag = A_TAG then
Collect_Link (Filter, Attributes, "href");
end if;
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end Push_Node;
end Wiki.Filters.Collectors;
|
-----------------------------------------------------------------------
-- wiki-filters-collectors -- Wiki word and link collectors
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Collectors is
procedure Add_String (Into : in out WString_Maps.Map;
Item : in Wiki.Strings.WString);
procedure Add_String (Into : in out WString_Maps.Map;
Item : in Wiki.Strings.WString) is
procedure Increment (Key : in Wiki.Strings.WString;
Value : in out Natural);
procedure Increment (Key : in Wiki.Strings.WString;
Value : in out Natural) is
pragma Unreferenced (Key);
begin
Value := Value + 1;
end Increment;
Pos : constant WString_Maps.Cursor := Into.Find (Item);
begin
if WString_Maps.Has_Element (Pos) then
Into.Update_Element (Pos, Increment'Access);
else
Into.Insert (Item, 1);
end if;
end Add_String;
function Find (Map : in Collector_Type;
Item : in Wiki.Strings.WString) return Cursor is
begin
return Map.Items.Find (Item);
end Find;
function Contains (Map : in Collector_Type;
Item : in Wiki.Strings.WString) return Boolean is
begin
return Map.Items.Contains (Item);
end Contains;
procedure Iterate (Map : in Collector_Type;
Process : not null access procedure (Pos : in Cursor)) is
begin
Map.Items.Iterate (Process);
end Iterate;
-- ------------------------------
-- Word Collector type
-- ------------------------------
procedure Collect_Words (Filter : in out Word_Collector_Type;
Content : in Wiki.Strings.WString) is
Pos : Natural := Content'First;
Start : Natural := Content'First;
C : Wiki.Strings.WChar;
begin
while Pos <= Content'Last loop
C := Content (Pos);
if Wiki.Strings.Is_Alphanumeric (C) then
null;
else
if Start + 1 < Pos - 1 then
Add_String (Filter.Items, Content (Start .. Pos - 1));
end if;
Start := Pos + 1;
end if;
Pos := Pos + 1;
end loop;
if Start < Content'Last then
Add_String (Filter.Items, Content (Start .. Content'Last));
end if;
end Collect_Words;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
Filter.Collect_Words (Text);
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Collect_Words (Header);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Filter_Type (Filter).Add_Quote (Document, Name, Attributes);
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Filter : in out Word_Collector_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Filter.Collect_Words (Text);
Filter_Type (Filter).Add_Preformatted (Document, Text, Format);
end Add_Preformatted;
procedure Collect_Link (Filter : in out Link_Collector_Type;
Attributes : in Wiki.Attributes.Attribute_List;
Name : in String) is
Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, Name);
begin
if Href'Length > 0 then
Add_String (Filter.Items, Href);
end if;
end Collect_Link;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Link_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Collect_Link (Filter, Attributes, "href");
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end Add_Link;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Link_Collector_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Tag = A_TAG then
Collect_Link (Filter, Attributes, "href");
end if;
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end Push_Node;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Image_Collector_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
Src : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, "src");
begin
Add_String (Filter.Items, Src);
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end Add_Image;
end Wiki.Filters.Collectors;
|
Implement Add_Image to collect images used in a wiki text
|
Implement Add_Image to collect images used in a wiki text
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
7af900c511cb689b4c14f7055853e39d40ad2719
|
posix-directory.adb
|
posix-directory.adb
|
with C_String;
with Interfaces.C;
with POSIX.C_Types;
with System;
package body POSIX.Directory is
--
-- Change_By_Descriptor.
--
procedure Change_By_Descriptor
(Descriptor : in File.Valid_Descriptor_t;
Error_Value : out Error.Error_t)
is
function Fchdir (Descriptor : in File.Valid_Descriptor_t)
return Error.Return_Value_t;
pragma Import (C, Fchdir, "fchdir");
begin
if Fchdir (Descriptor) = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end Change_By_Descriptor;
--
-- Change_By_Name.
--
procedure Change_By_Name
(Name : in String;
Error_Value : out Error.Error_t)
is
Descriptor : File.Descriptor_t;
Error_Local : Error.Error_t;
begin
File.Open_Read_Only
(File_Name => Name,
Non_Blocking => False,
Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local = Error.Error_None then
Change_By_Descriptor
(Descriptor => Descriptor,
Error_Value => Error_Value);
File.Close
(Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local /= Error.Error_None then
Error_Value := Error_Local;
end if;
else
Error_Value := Error_Local;
end if;
end Change_By_Name;
--
-- Create directory.
--
function Create_Boundary
(Name : in String;
Mode : in Permissions.Mode_t) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
--# hide Create_Boundary
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Mkdir
(Name : in C_String.String_Not_Null_Ptr_t;
Mode : in Permissions.Mode_t) return Error.Return_Value_t;
pragma Import (C, Mkdir, "mkdir");
begin
return Mkdir
(Name => C_String.To_C_String (C_Name'Unchecked_Access),
Mode => Mode);
end Create_Boundary;
procedure Create
(Name : in String;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t) is
begin
case Create_Boundary (Name, Mode) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Create;
--
-- Remove empty directory.
--
function Remove_Boundary (Name : in String) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
--# hide Remove_Boundary
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Rmdir (Name : in C_String.String_Not_Null_Ptr_t)
return Error.Return_Value_t;
pragma Import (C, Rmdir, "rmdir");
begin
return Rmdir (C_String.To_C_String (C_Name'Unchecked_Access));
end Remove_Boundary;
procedure Remove
(Name : in String;
Error_Value : out Error.Error_t) is
begin
case Remove_Boundary (Name) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Remove;
--
-- Retrieve current working directory.
--
procedure Get_Current_Boundary
(Name : out Path.Path_Name_t;
Name_Size : out Path.Path_Name_Size_t;
Error_Value : out Error.Error_t)
--# hide Get_Current_Boundary
is
use type C_String.String_Ptr_t;
function Getcwd
(Buffer : System.Address;
Size : C_Types.Size_t) return C_String.String_Ptr_t;
pragma Import (C, Getcwd, "getcwd");
Pointer : C_String.String_Ptr_t;
begin
Pointer := Getcwd
(Buffer => Name (Name'First)'Address,
Size => C_Types.Size_t (Path.Path_Name_Index_t'Last));
if Pointer = null then
Error_Value := Error.Get_Error;
Name_Size := 0;
else
Error_Value := Error.Error_None;
Name_Size := Path.Path_Name_Size_t (C_String.Length (Pointer));
end if;
end Get_Current_Boundary;
procedure Get_Current
(Name : out Path.Path_Name_t;
Name_Size : out Path.Path_Name_Size_t;
Error_Value : out Error.Error_t) is
begin
Get_Current_Boundary
(Name => Name,
Name_Size => Name_Size,
Error_Value => Error_Value);
end Get_Current;
end POSIX.Directory;
|
with C_String;
with Interfaces.C;
with POSIX.C_Types;
with System;
package body POSIX.Directory is
--
-- Change_By_Descriptor.
--
procedure Change_By_Descriptor
(Descriptor : in File.Valid_Descriptor_t;
Error_Value : out Error.Error_t)
is
function Fchdir (Descriptor : in File.Valid_Descriptor_t)
return Error.Return_Value_t;
pragma Import (C, Fchdir, "fchdir");
begin
if Fchdir (Descriptor) = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end Change_By_Descriptor;
--
-- Change_By_Name.
--
procedure Change_By_Name
(Name : in String;
Error_Value : out Error.Error_t)
is
Descriptor : File.Descriptor_t;
Error_Local : Error.Error_t;
begin
File.Open_Read_Only
(File_Name => Name,
Non_Blocking => False,
Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local = Error.Error_None then
Change_By_Descriptor
(Descriptor => Descriptor,
Error_Value => Error_Value);
File.Close
(Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local /= Error.Error_None then
Error_Value := Error_Local;
end if;
else
Error_Value := Error_Local;
end if;
end Change_By_Name;
--
-- Create directory.
--
function Create_Boundary
(Name : in String;
Mode : in Permissions.Mode_t) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
--# hide Create_Boundary
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Mkdir
(Name : in C_String.String_Not_Null_Ptr_t;
Mode : in Permissions.Mode_t) return Error.Return_Value_t;
pragma Import (C, Mkdir, "mkdir");
begin
return Mkdir
(Name => C_String.To_C_String (C_Name'Unchecked_Access),
Mode => Mode);
end Create_Boundary;
procedure Create
(Name : in String;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t) is
begin
case Create_Boundary (Name, Mode) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Create;
--
-- Remove empty directory.
--
function Remove_Boundary (Name : in String) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
--# hide Remove_Boundary
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Rmdir (Name : in C_String.String_Not_Null_Ptr_t)
return Error.Return_Value_t;
pragma Import (C, Rmdir, "rmdir");
begin
return Rmdir (C_String.To_C_String (C_Name'Unchecked_Access));
end Remove_Boundary;
procedure Remove
(Name : in String;
Error_Value : out Error.Error_t) is
begin
case Remove_Boundary (Name) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Remove;
--
-- Retrieve current working directory.
--
procedure Get_Current_Boundary
(Name : out Path.Path_Name_t;
Name_Size : out Path.Path_Name_Size_t;
Error_Value : out Error.Error_t)
--# global in Errno.Errno_Value;
--# derives Name, Name_Size, Error_Value from Errno.Errno_Value;
is
--# hide Get_Current_Boundary
use type C_String.String_Ptr_t;
function Getcwd
(Buffer : System.Address;
Size : C_Types.Size_t) return C_String.String_Ptr_t;
pragma Import (C, Getcwd, "getcwd");
Pointer : C_String.String_Ptr_t;
begin
Pointer := Getcwd
(Buffer => Name (Name'First)'Address,
Size => C_Types.Size_t (Path.Path_Name_Index_t'Last));
if Pointer = null then
Error_Value := Error.Get_Error;
Name_Size := 0;
else
Error_Value := Error.Error_None;
Name_Size := Path.Path_Name_Size_t (C_String.Length (Pointer));
end if;
end Get_Current_Boundary;
procedure Get_Current
(Name : out Path.Path_Name_t;
Name_Size : out Path.Path_Name_Size_t;
Error_Value : out Error.Error_t) is
begin
Get_Current_Boundary
(Name => Name,
Name_Size => Name_Size,
Error_Value => Error_Value);
end Get_Current;
end POSIX.Directory;
|
Update directory package for SPARK.
|
Update directory package for SPARK.
|
Ada
|
isc
|
io7m/coreland-posix-ada,io7m/coreland-posix-ada,io7m/coreland-posix-ada
|
762b513fbb4230c00ed4639d573735fa9e743ace
|
src/util-commands-parsers.ads
|
src/util-commands-parsers.ads
|
-----------------------------------------------------------------------
-- util-commands-parsers -- Support to parse command line options
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- === Command line parsers ===
-- Parsing command line arguments before their execution is handled by the
-- `Config_Parser` generic package. This allows to customize how the arguments are
-- parsed.
--
-- The `Util.Commands.Parsers.No_Parser` package can be used to execute the command
-- without parsing its arguments.
--
-- The `Util.Commands.Parsers.GNAT_Parser.Config_Parser` package provides support to
-- parse command line arguments by using the `GNAT` `Getopt` support.
package Util.Commands.Parsers is
-- The config parser that must be instantiated to provide the configuration type
-- and the Execute procedure that will parse the arguments before executing the command.
generic
type Config_Type is limited private;
with procedure Execute (Config : in out Config_Type;
Args : in Argument_List'Class;
Process : not null access
procedure (Cmd_Args : in Argument_List'Class)) is <>;
package Config_Parser is
end Config_Parser;
-- The empty parser.
type No_Config_Type is limited null record;
-- Execute the command with its arguments (no parsing).
procedure Execute (Config : in out No_Config_Type;
Args : in Argument_List'Class;
Process : not null access
procedure (Cmd_Args : in Argument_List'Class));
-- A parser that executes the command immediately (no parsing of arguments).
package No_Parser is
new Config_Parser (Config_Type => No_Config_Type,
Execute => Execute);
end Util.Commands.Parsers;
|
-----------------------------------------------------------------------
-- util-commands-parsers -- Support to parse command line options
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- === Command line parsers ===
-- Parsing command line arguments before their execution is handled by the
-- `Config_Parser` generic package. This allows to customize how the arguments are
-- parsed.
--
-- The `Util.Commands.Parsers.No_Parser` package can be used to execute the command
-- without parsing its arguments.
--
-- The `Util.Commands.Parsers.GNAT_Parser.Config_Parser` package provides support to
-- parse command line arguments by using the `GNAT` `Getopt` support.
package Util.Commands.Parsers is
-- The config parser that must be instantiated to provide the configuration type
-- and the Execute procedure that will parse the arguments before executing the command.
generic
type Config_Type is limited private;
with procedure Execute (Config : in out Config_Type;
Args : in Argument_List'Class;
Process : not null access
procedure (Cmd_Args : in Argument_List'Class)) is <>;
with procedure Usage (Name : in String;
Config : in out Config_Type) is <>;
package Config_Parser is
end Config_Parser;
-- The empty parser.
type No_Config_Type is limited null record;
-- Execute the command with its arguments (no parsing).
procedure Execute (Config : in out No_Config_Type;
Args : in Argument_List'Class;
Process : not null access
procedure (Cmd_Args : in Argument_List'Class));
procedure Usage (Name : in String;
Config : in out No_Config_Type) is null;
-- A parser that executes the command immediately (no parsing of arguments).
package No_Parser is
new Config_Parser (Config_Type => No_Config_Type,
Execute => Execute,
Usage => Usage);
end Util.Commands.Parsers;
|
Add a Usage procedure to the Config_Parser
|
Add a Usage procedure to the Config_Parser
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
7e83c8bd7554eba595ed3bffa8c4a63070303bbc
|
src/wiki-parsers-dotclear.adb
|
src/wiki-parsers-dotclear.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-dotclear -- Dotclear parser operations
-- Copyright (C) 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 Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Dotclear is
use Wiki.Helpers;
use Wiki.Nodes;
use Wiki.Strings;
use Wiki.Buffers;
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : constant Natural := Count_Occurence (Text, From, '/');
begin
if Count /= 3 then
return;
end if;
-- Extract the format either 'Ada' or '[Ada]'
declare
Pos : Natural := Count + 1;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Space_Count : Natural;
begin
Wiki.Strings.Clear (Parser.Preformat_Format);
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then
Next (Buffer, Pos);
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']',
Parser.Preformat_Format);
if Buffer /= null then
Next (Buffer, Pos);
end if;
else
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF,
Parser.Preformat_Format);
end if;
if Buffer /= null then
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
end if;
Text := Buffer;
From := Pos;
end;
Parser.Preformat_Indent := 0;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 0;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, N_PREFORMAT);
end Parse_Preformatted;
-- ------------------------------
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
procedure Append_Position (Position : in Wiki.Strings.WString);
procedure Append_Position (Position : in Wiki.Strings.WString) is
begin
if Position = "L" or Position = "G" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left");
elsif Position = "R" or Position = "D" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right");
elsif Position = "C" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center");
end if;
end Append_Position;
procedure Append_Position is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position);
Link : Wiki.Strings.BString (128);
Alt : Wiki.Strings.BString (128);
Position : Wiki.Strings.BString (128);
Desc : Wiki.Strings.BString (128);
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
if Block = null or else Block.Content (Pos) /= '(' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
if Block = null then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link);
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc);
end if;
end if;
end if;
end if;
-- Check for the first ')'.
if Block /= null and then Block.Content (Pos) = ')' then
Next (Block, Pos);
end if;
-- Check for the second ')', abort the image and emit the '((' if the '))' is missing.
if Block = null or else Block.Content (Pos) /= ')' then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Append_Position (Position);
Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Alt),
Parser.Attributes);
end if;
end Parse_Image;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Count : Natural;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
if Parser.In_Blockquote then
Count := Count_Occurence (Buffer, 1, '>');
if Count = 0 then
loop
Pop_Block (Parser);
exit when Parser.Current_Node = Nodes.N_NONE;
end loop;
else
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
end if;
end if;
if Parser.Current_Node = N_PREFORMAT then
if Parser.Preformat_Fcount = 0 then
Count := Count_Occurence (Buffer, 1, '/');
if Count /= 3 then
Common.Append (Parser.Text, Buffer, 1);
return;
end if;
Pop_Block (Parser);
return;
end if;
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Current_Node = N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
if C = '>' then
Count := Count_Occurence (Buffer, Pos, '>');
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
C := Buffer.Content (Pos);
end if;
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '!' =>
Common.Parse_Header (Parser, Buffer, Pos, '!');
if Buffer = null then
return;
end if;
when '/' =>
Parse_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
if Parser.Current_Node /= N_BLOCKQUOTE then
Pop_Block (Parser);
end if;
Push_Block (Parser, N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
Common.Parse_List (Parser, Buffer, Pos);
when others =>
if Parser.Current_Node /= N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '_' =>
Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD);
exit Main when Buffer = null;
when ''' =>
Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC);
exit Main when Buffer = null;
when '-' =>
Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT);
exit Main when Buffer = null;
when '+' =>
Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS);
exit Main when Buffer = null;
when ',' =>
Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT);
exit Main when Buffer = null;
when '@' =>
Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Quote (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '(' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '<' =>
Common.Parse_Template (Parser, Buffer, Pos, '<');
exit Main when Buffer = null;
when '%' =>
Count := Count_Occurence (Buffer, Pos, '%');
if Count >= 3 then
Parser.Empty_Line := True;
Flush_Text (Parser, Trim => Right);
if not Parser.Context.Is_Hidden then
Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK);
end if;
-- Skip 3 '%' characters.
for I in 1 .. 3 loop
Next (Buffer, Pos);
end loop;
if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then
Next (Buffer, Pos);
end if;
exit Main when Buffer = null;
else
Append (Parser.Text, C);
Pos := Pos + 1;
end if;
when CR | LF =>
-- if Wiki.Strings.Length (Parser.Text) > 0 then
Append (Parser.Text, ' ');
-- end if;
Pos := Pos + 1;
when '\' =>
Next (Buffer, Pos);
if Buffer = null then
Append (Parser.Text, C);
else
Append (Parser.Text, Buffer.Content (Pos));
Pos := Pos + 1;
Last := Buffer.Last;
end if;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Dotclear;
|
-----------------------------------------------------------------------
-- wiki-parsers-dotclear -- Dotclear parser operations
-- Copyright (C) 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 Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Dotclear is
use Wiki.Helpers;
use Wiki.Nodes;
use Wiki.Strings;
use Wiki.Buffers;
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : constant Natural := Count_Occurence (Text, From, '/');
begin
if Count /= 3 then
return;
end if;
-- Extract the format either 'Ada' or '[Ada]'
declare
Pos : Natural := Count + 1;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Space_Count : Natural;
begin
Wiki.Strings.Clear (Parser.Preformat_Format);
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then
Next (Buffer, Pos);
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']',
Parser.Preformat_Format);
if Buffer /= null then
Next (Buffer, Pos);
end if;
else
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF,
Parser.Preformat_Format);
end if;
if Buffer /= null then
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
end if;
Text := Buffer;
From := Pos;
end;
Parser.Preformat_Indent := 0;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 0;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, N_PREFORMAT);
end Parse_Preformatted;
-- ------------------------------
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
procedure Append_Position (Position : in Wiki.Strings.WString);
procedure Append_Position (Position : in Wiki.Strings.WString) is
begin
if Position = "L" or Position = "G" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left");
elsif Position = "R" or Position = "D" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right");
elsif Position = "C" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center");
end if;
end Append_Position;
procedure Append_Position is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position);
Link : Wiki.Strings.BString (128);
Alt : Wiki.Strings.BString (128);
Position : Wiki.Strings.BString (128);
Desc : Wiki.Strings.BString (128);
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
if Block = null or else Block.Content (Pos) /= '(' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
if Block = null then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link);
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc);
end if;
end if;
end if;
end if;
-- Check for the first ')'.
if Block /= null and then Block.Content (Pos) = ')' then
Next (Block, Pos);
end if;
-- Check for the second ')', abort the image and emit the '((' if the '))' is missing.
if Block = null or else Block.Content (Pos) /= ')' then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Append_Position (Position);
Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Alt),
Parser.Attributes);
end if;
end Parse_Image;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Count : Natural;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
if Parser.In_Blockquote then
Count := Count_Occurence (Buffer, 1, '>');
if Count = 0 then
loop
Pop_Block (Parser);
exit when Parser.Current_Node = Nodes.N_NONE;
end loop;
else
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
end if;
end if;
if Parser.Current_Node = N_PREFORMAT then
if Parser.Preformat_Fcount = 0 then
Count := Count_Occurence (Buffer, 1, '/');
if Count /= 3 then
Common.Append (Parser.Text, Buffer, 1);
return;
end if;
Pop_Block (Parser);
return;
end if;
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Current_Node = N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
if C = '>' then
Count := Count_Occurence (Buffer, Pos, '>');
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
C := Buffer.Content (Pos);
end if;
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '!' =>
Common.Parse_Header (Parser, Buffer, Pos, '!');
if Buffer = null then
return;
end if;
when '/' =>
Parse_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
if Parser.Current_Node /= N_BLOCKQUOTE then
Pop_Block (Parser);
end if;
Push_Block (Parser, N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
Common.Parse_List (Parser, Buffer, Pos);
when others =>
if Parser.Current_Node /= N_PARAGRAPH and Parser.Current_Node /= N_BLOCKQUOTE then
Pop_List (Parser);
Push_Block (Parser, N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '_' =>
Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD);
exit Main when Buffer = null;
when ''' =>
Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC);
exit Main when Buffer = null;
when '-' =>
Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT);
exit Main when Buffer = null;
when '+' =>
Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS);
exit Main when Buffer = null;
when ',' =>
Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT);
exit Main when Buffer = null;
when '@' =>
Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Quote (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '(' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '<' =>
Common.Parse_Template (Parser, Buffer, Pos, '<');
exit Main when Buffer = null;
when '%' =>
Count := Count_Occurence (Buffer, Pos, '%');
if Count >= 3 then
Parser.Empty_Line := True;
Flush_Text (Parser, Trim => Right);
if not Parser.Context.Is_Hidden then
Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK);
end if;
-- Skip 3 '%' characters.
for I in 1 .. 3 loop
Next (Buffer, Pos);
end loop;
if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then
Next (Buffer, Pos);
end if;
exit Main when Buffer = null;
else
Append (Parser.Text, C);
Pos := Pos + 1;
end if;
when CR | LF =>
-- if Wiki.Strings.Length (Parser.Text) > 0 then
Append (Parser.Text, ' ');
-- end if;
Pos := Pos + 1;
when '\' =>
Next (Buffer, Pos);
if Buffer = null then
Append (Parser.Text, C);
else
Append (Parser.Text, Buffer.Content (Pos));
Pos := Pos + 1;
Last := Buffer.Last;
end if;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Dotclear;
|
Update formatting of blockquotes
|
Update formatting of blockquotes
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
78b232f6fbc7ffbea39c5dbbeac8ec8325bba39a
|
src/security-oauth.ads
|
src/security-oauth.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
end Security.OAuth;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
-- RFC 6749: 4.1.2.1. Error Response
ACCESS_DENIED : aliased constant String := "access_denied";
UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type";
SERVER_ERROR : aliased constant String := "server_error";
TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable";
end Security.OAuth;
|
Define errors for RFC 6749: 4.1.2.1. Error Response
|
Define errors for RFC 6749: 4.1.2.1. Error Response
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
9d81690b1d2b32a976a5a6e6d799b44883d20f03
|
src/asf-helpers-beans.adb
|
src/asf-helpers-beans.adb
|
-----------------------------------------------------------------------
-- asf-helpers-beans -- Helper packages to write ASF applications
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
package body ASF.Helpers.Beans is
-- ------------------------------
-- Get a bean instance associated under the given name from the current faces context.
-- A null value is returned if the bean does not exist or is not of the good type.
-- ------------------------------
function Get_Bean (Name : in String) return Element_Access is
use type ASF.Contexts.Faces.Faces_Context_Access;
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return null;
end if;
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Context.Get_Bean (Name);
begin
if Bean = null or else not (Bean.all in Element_Type'Class) then
return null;
else
return Element_Type'Class (Bean.all)'Access;
end if;
end;
end Get_Bean;
end ASF.Helpers.Beans;
|
-----------------------------------------------------------------------
-- asf-helpers-beans -- Helper packages to write ASF applications
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Contexts.Faces;
package body ASF.Helpers.Beans is
-- ------------------------------
-- Get a bean instance associated under the given name from the current faces context.
-- A null value is returned if the bean does not exist or is not of the good type.
-- ------------------------------
function Get_Bean (Name : in String) return Element_Access is
use type ASF.Contexts.Faces.Faces_Context_Access;
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return null;
end if;
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Context.Get_Bean (Name);
begin
if Bean = null or else not (Bean.all in Element_Type'Class) then
return null;
else
return Element_Type'Class (Bean.all)'Access;
end if;
end;
end Get_Bean;
-- ------------------------------
-- Get a bean instance associated under the given name from the request.
-- A null value is returned if the bean does not exist or is not of the good type.
-- ------------------------------
function Get_Request_Bean (Request : in ASF.Requests.Request'Class;
Name : in String) return Element_Access is
Value : constant Util.Beans.Objects.Object := Request.Get_Attribute (Name);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null or else not (Bean.all in Element_Type'Class) then
return null;
else
return Element_Type'Class (Bean.all)'Access;
end if;
end Get_Request_Bean;
end ASF.Helpers.Beans;
|
Implement the generic function Get_Request_Bean
|
Implement the generic function Get_Request_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0649eaf0e851e1e1c2455c906a86998e1a520caf
|
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 := "88";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.26";
default_pgsql : constant String := "9.6";
default_php : constant String := "7.1";
default_python3 : constant String := "3.6";
default_ruby : constant String := "2.4";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc7";
compiler_version : constant String := "7.2.0";
previous_compiler : constant String := "7.1.0";
binutils_version : constant String := "2.29.1";
previous_binutils : constant String := "2.29";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "0";
raven_version_minor : constant String := "89";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.26";
default_pgsql : constant String := "9.6";
default_php : constant String := "7.1";
default_python3 : constant String := "3.6";
default_ruby : constant String := "2.4";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc7";
compiler_version : constant String := "7.2.0";
previous_compiler : constant String := "7.1.0";
binutils_version : constant String := "2.29.1";
previous_binutils : constant String := "2.29";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version for postgresql option change
|
Bump version for postgresql option change
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
981d1d398b2329f264a92b53dd8cf0ac993eddfb
|
src/util-concurrent-pools.ads
|
src/util-concurrent-pools.ads
|
-----------------------------------------------------------------------
-- Util.Concurrent.Pools -- Concurrent Pools
-- 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.Finalization;
-- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which
-- can be shared by multiple threads. First, the pool is configured to have
-- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread
-- that needs an object uses the <b>Get_Instance</b> to get an object.
-- The object is removed from the pool. As soon as the thread has finished,
-- it puts back the object in the pool using the <b>Release</b> procedure.
--
-- The <b>Get_Instance</b> entry will block until an object is available.
generic
type Element_Type is private;
package Util.Concurrent.Pools is
-- Pool of objects
type Pool is new Ada.Finalization.Limited_Controlled with private;
-- Get an element instance from the pool.
-- Wait until one instance gets available.
procedure Get_Instance (From : in out Pool;
Item : out Element_Type);
-- Put the element back to the pool.
procedure Release (Into : in out Pool;
Item : in Element_Type);
-- Set the pool size.
procedure Set_Size (Into : in out Pool;
Capacity : in Positive);
-- Release the pool elements.
overriding
procedure Finalize (Object : in out Pool);
private
-- To store the pool elements, we use an array which is allocated dynamically
-- by the <b>Set_Size</b> protected operation. The generated code is smaller
-- compared to the use of Ada vectors container.
type Element_Array is array (Positive range <>) of Element_Type;
type Element_Array_Access is access all Element_Array;
Null_Element_Array : constant Element_Array_Access := null;
-- Pool of objects
protected type Protected_Pool is
-- Get an element instance from the pool.
-- Wait until one instance gets available.
entry Get_Instance (Item : out Element_Type);
-- Put the element back to the pool.
procedure Release (Item : in Element_Type);
-- Set the pool size.
procedure Set_Size (Capacity : in Natural);
private
Available : Natural := 0;
Elements : Element_Array_Access := Null_Element_Array;
end Protected_Pool;
type Pool is new Ada.Finalization.Limited_Controlled with record
List : Protected_Pool;
end record;
end Util.Concurrent.Pools;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Pools -- Concurrent Pools
-- 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.Finalization;
-- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which
-- can be shared by multiple threads. First, the pool is configured to have
-- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread
-- that needs an object uses the <b>Get_Instance</b> to get an object.
-- The object is removed from the pool. As soon as the thread has finished,
-- it puts back the object in the pool using the <b>Release</b> procedure.
--
-- The <b>Get_Instance</b> entry will block until an object is available.
generic
type Element_Type is private;
package Util.Concurrent.Pools is
pragma Preelaborate;
-- Pool of objects
type Pool is new Ada.Finalization.Limited_Controlled with private;
-- Get an element instance from the pool.
-- Wait until one instance gets available.
procedure Get_Instance (From : in out Pool;
Item : out Element_Type);
-- Put the element back to the pool.
procedure Release (Into : in out Pool;
Item : in Element_Type);
-- Set the pool size.
procedure Set_Size (Into : in out Pool;
Capacity : in Positive);
-- Release the pool elements.
overriding
procedure Finalize (Object : in out Pool);
private
-- To store the pool elements, we use an array which is allocated dynamically
-- by the <b>Set_Size</b> protected operation. The generated code is smaller
-- compared to the use of Ada vectors container.
type Element_Array is array (Positive range <>) of Element_Type;
type Element_Array_Access is access all Element_Array;
Null_Element_Array : constant Element_Array_Access := null;
-- Pool of objects
protected type Protected_Pool is
-- Get an element instance from the pool.
-- Wait until one instance gets available.
entry Get_Instance (Item : out Element_Type);
-- Put the element back to the pool.
procedure Release (Item : in Element_Type);
-- Set the pool size.
procedure Set_Size (Capacity : in Natural);
private
Available : Natural := 0;
Elements : Element_Array_Access := Null_Element_Array;
end Protected_Pool;
type Pool is new Ada.Finalization.Limited_Controlled with record
List : Protected_Pool;
end record;
end Util.Concurrent.Pools;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.