REST easy with kbmMW #5 – Logging

Following up on the previous blog posts about how easily to create a REST server with kbmMW, I today want to write a little bit about logging.

kbmMW contains a quite sophisticated logging system, which lets the developer log various types of information whenever the developer needs it, and at runtime lets the administrator decide what type of log to react on and how.

In addition the log can be output in a file, in the system log (OS dependant), or be sent to a remote computer for storage. In fact all the above methods can coexist at once.

What’s the purpose of logging?

Well. There can be multiple purposes, amongst others:

  • For debugging while developing
  • For debugging after deployment
  • For keeping track of resources
  • For keeping track of usage (perhaps even relates to later invoicing)
  • For proving reasons for user complaints
  • Of security reasons to track who is doing what

As you can tell, there seems to be various log requirements for various stages of the lifetime of the application:

  • During development
  • During usage
  • Early warning
  • Post incident investigation

A good log system should imo handle all the above scenarios, while making it simple to use for the developer, and allow the administrator to tune on the amount of information needed.

kbmMW’s log system handles all these scenarios, and can be late fine tuned for the required log level.

In addition the log system should be able to output the log in relevant formats, that match the application’s purpose.

Web server applications, might want to output some log data in a format generally accepted by web servers, and thus also by web server log file analyzer software, while other server applications may have other requirements for output.

kbmMW supports several output formats, and also allows adding additional formats, without having to make changes in the developer’s logging statements.

So let us get on with it.

First add the kbmMWLog unit to the units in which you expect to do some logging.

In our case, we have the units Unit7 (main form unit), Unit8 (Smart service unit… the actual REST business code) and Unit9 (a defined sharable TContact object).

It makes sense to add support for logging in Unit7 and Unit8. In Unit7 it would look similar to this:

interface

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, kbmMWCustomTransport, kbmMWServer,
 kbmMWTCPIPIndyServerTransport, kbmMWRESTTransStream,
 kbmMWCustomConnectionPool, kbmMWCustomSQLMetaData, kbmMWSQLiteMetaData,
 kbmMWSQLite, kbmMWORM, IdBaseComponent, IdComponent, IdServerIOHandler, IdSSL,
 IdSSLOpenSSL, IdContext, kbmMWSecurity, kbmMWLog;

And in Unit8 we have also added kbmMWLog to the uses clause.

By simply adding this unit, we can already log by calling one of the methods of the public default available Log instance. Eg.

Log.Debug('some debug information');
Log.Info('2 + 2 = %d',[2+2]);

kbmMW’s log system supports these easy access methods:

  • Debug (typically used during development purposes),
  • Info (inform about some non critical and non error like information)
  • Warn (inform about some non critical anormal situation)
  • Error (inform about some error, like an exception or something else which still allow the application to continue to operate)
  • Fatal (inform about an error of such magnitude that the application no longer can run).
  • Audit (inform about some information that you want to be used as evidence in a post analysis scenario).

They in turn calls a number of generic TkbmMWLog.Log method which takes arguments for log type, severity, timestamps and much more.

You can ask kbmMW to log content of streams, of memory buffers, XML and JSON documents, byte arrays, and you can even ask kbmMW to produce a stack trace along with your log (not currently supported on NextGen platforms).

In our simple REST server, we might want to log whenever a user logs in, when they are logged out, when a function is called, and when an exception happens.

To intercept the login situation, we will write some event handlers for the OnLoginSuccess and OnLoginFailed event on the TkbmMWAuthorizationManager instance we have on Unit7.

procedure TForm7.kbmMWAuthorizationManager1LoginFail(Sender: TObject;
 const AActorName, ARoleName, AMessage: string);
begin
 Log.Warn('Failed login attempt as %s with role %s. %s',[AActorName,ARoleName,AMessage]);
end;

procedure TForm7.kbmMWAuthorizationManager1LoginSuccess(Sender: TObject;
 const AActorName, ARoleName: string; const AActor: TkbmMWAuthorizationActor;
 const ARole: TkbmMWAuthorizationRole);
begin
 Log.Info('Logged in as %s with role %s',[AActorName,ARoleName]);
end;

It makes sense to log a successful login as an information, while an unsuccessful login is logged as a warning. If it happens often, it could be malicious login attempts, so warnings ought to be looked after.

And we might also want to log a logout of a user. The logout may happen automatically due to the user being idle for too long. Refer to the previous blog post for more information.

We might also want to log what calls are made by logged in users.

This can be done in many ways and many places. You could choose to do it within your business logic code in the smart service in Unit8, which makes sense if you want to log some more specific information about the call.

But if you just want to log successful and failed calls, then it’s easy to do so using the OnServeResponse event of the TkbmMWServer instance in Unit7.

As long as the request is formatted correctly and thus served through the TkbmMWServer, it will be attempted to be executed, and a response sent back to the caller.

The execution may succeed or it may fail, but in all cases the OnServeResponse event will be triggered.

procedure TForm7.kbmMWServer1ServeResponse(Sender: TObject;
 OutStream: IkbmMWCustomResponseTransportStream; Service: TkbmMWCustomService;
 ClientIdent: TkbmMWClientIdentity; Args: TkbmMWVariantList);
begin
 if OutStream.IsOK then
   Log.Info('Successfully called %s on service %s',[ClientIdent.Func,ClientIdent.ServiceName])
 else
   Log.Error('An error "%s" happened while serving request for %s on %s',[ClientIdent.Func,ClientIdent.ServiceName,OutStream.StatusText]);
end;

Now we intercepts and logs at strategic places in our code, and in fact the logging is already working. But the log output is currently only placed on the system log, which on Windows is interpreted as the debugger.

We need to have our log output to a file, preferably with nice chunking when the file reach a certain size.

The responsibility of the actual output, is the log manager. There are a number of log managers included with kbmMW:

  • TkbmMWStreamLogManager – Sends log to a TStream descendant.
  • TkbmMWLocalFileLogManager – Sends log to a file.
  • TkbmMWSystemLogManager – Sends log to system log (depends on OS).
  • TkbmMWStringsLogManager – Sends log to a TStrings descendant.
  • TkbmMWProxyLogManager – Proxies log to another log manager.
  • TkbmMWTeeLogManager – Sends log to a number of other log managers.
  • TkbmMWNullLogManager – Sends log to the bit graveyard.

If you have kbmMW Enterprise Edition and thus also have access to the WIB (Wide Information Bus) publish/subscribe transports, you have a couple of additional log managers available for remote logging:

  • TkbmMWClientLogManager – Publishes logs via the WIB
  • TkbmMWServerLogManager – Subscribes for logs on the WIB, and forwards those through other log managers.

You can make your own log manager by descending from TkbmMWCustomLogManager and implementing the IkbmMWLogManager interface.

To use a different log manager than the default system log manager, you simply create an instance of the log manager you want to use and assign it to the TkbmMWLog.Log.LogManager property. Eg.

Log.LogManager:=TkbmMWLocalFileLogManager.Create('c:\temp\mylogfile.log');

However to set specific settings on the log manager, it is better to instantiate a variable with it, set its properties and then later assign that variable to the Log.LogManager property.

An even easier way, is to use one of the Log.Output….. methods, which easily creates relevant log managers for you with settings that usually are good for most circumstances. Eg.

Log.OutputToDefaultAndFile('c:\temp\mylogfile.log');

This will in fact create 3 log managers, a system log manager, a file log manager and a tee log manager and automatically hooks them all up.

In our case we just want to output to a file, so let us stick with the TkbmMWLocalFileLogManager. So we will simply create an instance and assign it to the Log.LogManager as shown above.

Now all the log will be output to the file, and the file will automatically be backed up and a new created when it reaches 1MB size. Backup naming and size etc. are all configurable on the TkbmMWLocalFileLogManager instance.

You can control which fields are output via the Log.LogManager.LogFormatter property. It is default a TkbmMWStandardLogFormatter. kbmMW also supports a TkbmMWSimpleLogFormatter which only outputs date/time, type and the actual log string.

The standard log formatter also outputs data type, process and thread information and binary data (usually converted to either Base64 or hexdump (pretty) format).

There are much more to logging. We didn’t touch the fact that the log system can handle separate log files for auditing and other logging, and that you can set filtering on each log manager so that particular log manager only logs certain log types or log levels or data types.

Happy logging.

ANN: kbmMW Professional and Enterprise Edition v. 5.02.00 released!

We are happy to announce v5.02 of our popular middleware for Delphi and
C++Builder.

If you like kbmMW, please let others know! Share the word!

We strive hard to ensure kbmMW continues to set the bar for what an n-tier product must be capable of in the real world!

Keywords for this release:

  • Many ORM improvements
  • New! CRON compatible scheduler support
  • Synchronous encryption improvements
  • AMQP improvements
  • Many other improvements and bugfixes for reported bugs

Please look in the end of this post for a detailed change list.

Professional and Enterprise Edition is available for all with a current
active SAU. If your SAU has run out, please visit our shop to extend it with another
12 months.

CodeGear Edition is available for free, but only supports a specific Delphi/Win32 SKU, contains a limited feature set and do not include source.

Please visit https://portal.components4developers.com to download.

—-

kbmMW is the premiere n-tier product for Delphi, C++Builder and FPC on .Net, Win32, Win64, Linux, Java, PHP, Android, IOS, embedded devices, websites, mainframes and more.

Please visit http://www.components4developers.com for more information about kbmMW.

—-

Components4Developers is a company established in 1999 with the purpose of providing high quality development tools for developers and enterprises. The primary focus is on SOA, EAI and systems integration via our flagship product kbmMW.

kbmMW is a portable, highly scalable, high end application server and enterprise architecture integration (EAI) development framework for Win32, ..Net and Linux with clients residing on Win32, .Net, Linux, Unix, Mainframes, Minis, Embedded and many other places. It is currently used as the backbone in hundreds of central systems, in
hospitals, courts, private, industries, offshore industry, finance, telecom, governements, schools, laboratories, rentals, culture institutions, FDA approved medical devices, military and more.


5.02.00 May 27 2017

Important notes (changes that may break existing code)
======================================================
* Changed Use class in kbmMWSmartUtils.pas. Now it will use TkbmMWAutoValue internally
to store data. Since data stored in TkbmMWAutoValue is reference counted and scoped,
access to the data is slightly different.
Use AsObject to return a reference to the object. Ownership of the object belongs to the TkbmMWAutoValue container.
Use AsMyObject to return a reference to the object and mark it as your object. You will be responsible for freeing it.

New stuff
=========
– Added IkbmMWAutoValue and TkbmMWAutoValue to kbmMWGlobal.pas. They handle scope based object life time handling.
– Changed smart object’s (TkbmMWMarshalledVariantData) to use TkbmMWAutoValue.
– Updated DumpVariant in kbmMWGlobal.pas to dump smart object’s too.
– Added support for TkbmMWTiming on IOS.
– Added support for REST tags anonymousRoot=true/false and pretty=true/false which
can be used to control if resulting objects should be anonymous or contained in a
parent object, and if the result should be prettyformatted or not (default).
Prettyformatting is not implemented on JSON at the time.
– Updated AMQP protocol to default not write shortstrings, unsigned 8bit, unsigned16 bit
unsigned32 bit and unsigned 64 bit. Reason is that although AMQP v. 0.9.1
should support them, industry dont, why most AMQP implementations will not understand those types.
It is possible to uncommnet a number of defines in top of kbmMWAMQP.pas to selectively
enable these types. If they are commented, kbmMW auto propogates the value to the next
sensible type.
– Updated kbmMWAMQP.pas to support copying field tables instead of assigning them.
– Added Safe property to TkbmMWMixerPasswordGen. If set to true, it will not use
digits and characters that can be visually misread (0 vs O etc).
– Added OnMessageProcessingFailed event to TkbmMWCustomSAFClientTransport and
TkbmMWCUstomSAFServerTransport and published in descending classes.
It will be called when message processing failed, for example if kbmMW is
unable to decrypt a message.
– Added support for dynamic arrays in object marshalling.
– Added support for Notify in TkbmMWDateTime and kbmMWNullable. If set (in an ORM scenario)
the client will be notified about the value in that particular field.
– Modified and fixed timezone initialization in kbmMWDateTime.pas.
– Added OutputToDefaultAndFile and OutputToDefaultAndStringsAndFile to TkbmMWLog for
easy setup of outputs.
– Enhanced TkbmMWCustomCrypt to support PassPhraseBytes (which if set, takes precedence over
PassPhrase (string).
– Added OnEncryptKeys, OnDecryptKeys, OnDecryptStatus events to TkbmMWCustomCrypt to allow for
attempting various keys before finally either succeeding or giving up.
This can be valuable in supporting client unique encryption/decryption.
– Added a number of GetDefAs…. methods to TkbmMWONArray and TkbmMWONObject which
returns a default value if the property/index is missing instead of raising an exception.
– Added GlobalIndexNames property to TkbmMWCustomSQLMetaData. If set kbmMW’s SQL rewriter
knows that index names must be database scope unique, instead of only table scope unique.
– Added Init function that accepts a string as salt to TkbmMWCustomHash.
– Added GetDigest to TkbmMWCustomHash, which returns a byte array with the digested hash.
Its an alternative to using Final.
– Added OnDisconnected and OnException events to TkbmMWAMQPClientConnection.
– Added OnConnect, OnDisconnect, OnDisconnected and OnException events to TkbmMWAMQPClient.
– Added mwsloDateTimeIsUTC to TkbmMWSQLiteOption. Determines how to interpret date time values, as local time or as UTC time.
– Added support for boolean parameter values in TkbmMWSQLite.
– Improved marshalling of kbmMWNullable types.
– Added kbmMWSubjectGetType, kbmMWSubjectExtractNodeID and
kbmMWGenerateMessageSubscriptionSubject to kbmMWSubjectUtils.pas
– Added mwrieNotify to TkbmMWRecordInfoEvent in kbmMWCustomDataset.pas
– Added support for TIMESTAMP datatype in SQL datatype deduction.
– Added support for returning an interfaced object from smart services.
– Added field change detection to TkbmMWFieldDefs.
– Improved TkbmMWRTTI.InstantiateValue in kbmMWRTTI.pas.
– Improved kbmMWNullable.
– Changed Use class in kbmMWSmartUtils.pas. Now it will use TkbmMWAutoValue internally
to store data. Since data stored in TkbmMWAutoValue is reference counted and scoped,
access to the data is slightly different.
Use AsObject to return a reference to the object. Ownership of the object belongs to the TkbmMWAutoValue container.
Use AsMyObject to return a reference to the object and mark it as your object. You will be responsible for freeing it.
– Added methods ToDataset, FromDataset, ListFromDataset to TkbmMWSmartClientORM.
Provides an easy way to convert arguments and results to and from datasets.
– Added Cron fluent method to IkbmMWScheduledEvent. It accepts a 5 or 6 part Unix cron value
which defines the interval.
– Added AtYears, AtMonths, AtDays, AtHours, AtMinutes, AtSeconds methods to IkbmMWScheduledEvent
to give an alternative way to provide cron like schedules.
– Added SynchronizedAfterRun and AfterRun methods to IkbmMWScheduledEvent to
provide an anonymous function to be called after the schedule has run.
It is particular valuable on scheduling asynchronous operations via RunNow,
followed up with updating something with the result of the function.
– Added TkbmMWONSchedulerStorage for storing/retrieving schedules in any object notation format.
– Added support for subscribing for raw messages using anonymous function in WIB.
– Added Delete to TkbmMWORM taking primary key values alternative specific field values.
– Added support for many more date formats for ORM data generators.
In addition to LOCAL, UTC and ISO8601, also RFC1123, NCSA, LOCALSINCEEPOCHMS,
UTCSINCEEPOCHMS, LOCALSINCEEPOCH and UTCSINCEEPOCH is supported.
– Generally many additional improvements on ORM.

Fixes
=====
– Fixed default true/false values for TkbmMWSQLiteMetaData.
– Fixed HTTP/REST/AJAX additional incorrect CRLF in output.
– Fixed serious bug in 32 bit random generators (kbmMWRandom.pas).
– Fixed NextGen issues in some parsing routines in kbmMWDateTime.pas.
– Fixed bugs in Query service wizard.
– Fixed some SQL rewriting bugs including adding support for DESCENDING order by.

REST easy with kbmMW #4 – Access management

Building on the previous articles about how to create a REST server using kbmMW, we have now reached the stage where we should consider access management.

What is access management? It’s the “science of who are allowed to do what.

It is obvious that data exists in this world, which should be protected from being read, created or altered by people/processes we have not authorized to do so. Or turned on its head, some data should be protected and be accessible only by people/processes that we trust.

Other data might be left freely available for reading, but never for modifying and so forth.

Fortunately kbmMW have features built in to support us with that.

We start by adding a TkbmMWAuthorizationManager to the main form (Unit7 in the previous posts).2017-05-26 15_07_56-Project6 - RAD Studio 10.1 Berlin - Unit7.png

We can use the authorization manager as is, standalone, but it often makes sense to connect it to the kbmMWServer instance. Thus set the property kbmMWServer1.AuthorizationManager to point on kbmMWAuthorizationManager1.

This way, every call into the application server will checked by the authorization manager for access rights.

The kbmMW authorization manager is an entity which understands the topics:

  • resource
  • actor
  • role
  • authorization
  • constraint
  • login

A resource is basically anything that you want to add some sort of protection for. It can be database related, it can be a specific object, it can be a function or a service that you want to ensure is only handled in ways that you want it to, by people/processes that you have granted access to it. Resources can be grouped in resource trees, where having access to one resource also automatically provides same access to resources underneath that resource.

An actor, is typically a person (or a person’s login credentials), a process or something else that identifies “someone” that want access to your resource’s.

A role is a way to categorize general access patterns. Roles in a library, could be a librarian, an administrator and a loaner. Roles in a bank could be a customer, a teller, a clerk, an administrator and so forth. The idea is that each of the roles will have different access rights to the various resources. Actors usually will be given at least one role. An actor can have different roles, for example depending on how the actor log’s in, or from where.

An authorization is a “license” to operate as an actor or a role on a specific resource. An authorization can be negative, thus specifically denying an actor or role access to specific resources and their subtrees.

A constraint is a limitation to an authorization or to a login. The authorization may only be valid within a specific timeframe, or be allowed to be accessed from specific equipment and such, or the login can only happen during daytime etc.

A login is the match between an actor/password and a login token. When an actor is attempting to be logged in, the system verifies login name, password, requested role and whatever constraints has been defined related to login in. Only when everything has been checked up and a login is allowed, a token is issued, which the actor/user/process will need to send along with every request it makes to the kbmMW based server.

So let us define two roles we want to have access to our REST server. We can choose to name them ‘Reader’ and ‘ReadWriter’, but as kbmMW do not pose any restrictions to naming of roles (nor on actors and resources), we can name them anything as long as the names are unique within their category (roles, actors, resources).

  • Reader
  • ReadWriter

In code we define the roles like this (for example in the OnCreate event of the main form:

 kbmMWAuthorizationManager1.AddRole('READER');
 kbmMWAuthorizationManager1.AddRole('READWRITER');

We also, somehow, need to tell the authorization manager which actors exists so it can match up login attempts with actors.

The simple way is to predefine them to the authorization manager. That can for example also happen in the OnCreate event of the form, or elsewhere before the first access to the server. The actors can be defined from a database or a configuration file or LDAP etc. as needed.

 kbmMWAuthorizationManager1.AddActor('HANS','HANSPASSWORD','READER');
 kbmMWAuthorizationManager1.AddActor('CHRISTINE','CHRISTINEPASSWORD','READWRITER');

This defines two actors with their passwords, and which role they should act as upon login if they do not specifically ask for a different role.

It is possible not to predefine actors, but instead use an event handler to verify their existence in a different system via the OnLogin event of the kbmMWAuthorizationManager1 instance.

procedure TForm7.kbmMWAuthorizationManager1Login(Sender: TObject;
 const AActorName, ARoleName: string; var APassPhrase: string;
 var AActor: TkbmMWAuthorizationActor; var ARole: TkbmMWAuthorizationRole;
 var AMessage: string);
begin
...
end;

An AActorName and the requested role name in ARoleName is provided. Optionally an actor instance may also be provided, if the actorname is known to kbmMW. If not, AActor is nil, and must be created by you if you know about the actor.

ARole may be nil, if it’s an unknown role that is requested. You can choose to define the role on the fly by returning a newly created TkbmMWAuthorizationRole instance. Remember to add any newly created actor or role instances to the kbmMWAuthorizationManagers Actors and Roles list properties before returning.

APassword will contain the password delivered with the login attempt. You are allowed to modify it on the fly (for example to change it to a SHA256 hash, so no human readable passwords are stored in the authorization manager).

If you return nil for AActor or ARole, then it means that the login failed. You can provide an explanation in the AMessage argument if you want.

But let us continue with our simple actor definition for this sample

Now that we have actors and roles defined, the authorization manager is ready to handle login attempts.

There is only one way to login, and that is by calling the Login method of the authorization manager. This can, for example, be called from a new REST function in your REST service.

An alternative is to let kbmMW automatically detect login attempts, and call the Login method for you. To do that, set the Options property of kbmMWAutorizationManager1 to [mwaoAutoLogin].

As you may remember, all requests to the kbmMW server must be accompanied with a Token identifying a valid login. If that token is not available, kbmMW (with mwaoAutoLogin set), is triggered to use whatever username/password passed on from the caller, as data for a login attempt and will return the token back to the called if the login succeeded.

As a REST server is essentially a web server, adhering to the HTTP protocol standards, what happens when kbmMW detects an invalid (or non existing) login, is that kbmMW will raise an EkbmMWAuthException, which in turn (when the call comes via the REST streamformat), will be translated into an HTTP error 401, which is presented to the caller. In fact, if you would raise that exception anywhere within your business code and you do not manage it yourself, it will automatically be forwarded to the caller as a 401.

This will prompt most browsers to present a login dialog, where username/password can be entered, and next call to back to the server, will include that login information. kbmMW will automatically detect this and use it.

So we have actor, role and login in place. Now we need to determine what resources we have. A resource can be anything you want to tag a unique name on.

Most of the time, it makes sense to define REST methods as a resource. This is done very easily in our smart service, where we have the functions for manipulating and retrieving contacts (Unit8). We use the kbmMW_Auth attribute.

[kbmMW_Service('name:MyREST, flags:[listed]')]
[kbmMW_Rest('path:/MyREST')]
TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
 public
  [kbmMW_Auth('role:[READER,READWRITER], grant:true')]
  [kbmMW_Rest('method:get, path:helloworld, anonymousResult:true')]
  [kbmMW_Method]
  function HelloWorld:TMyResult;

  [kbmMW_Auth('role:[READER,READWRITER], grant:true')]
  [kbmMW_Rest('method:get, path:contacts, anonymousResult:true')]
  function GetContacts:TObjectList<TContact>;

  [kbmMW_Auth('role:[READWRITER], grant:true')]
  [kbmMW_Rest('method:put, path:addcontact')]
  function AddContact([kbmMW_Rest('value:"{$name}"')] const AName:string;
    [kbmMW_Rest('value:"{$address}"')] const AAddress:string;
    [kbmMW_Rest('value:"{$zipcode}"')] const AZipCode:string;
    [kbmMW_Rest('value:"{$city}"')] const ACity:string):string; overload;

  [kbmMW_Auth('role:[READWRITER], grant:true')]
  [kbmMW_Rest('method:get, path:"addcontact/{name}"')]
  function AddContact([kbmMW_Rest('value:"{name}"')] const AName:string):string; overload;

  [kbmMW_Auth('role:[READWRITER], grant:true')]
  [kbmMW_Rest('method:delete, path:"contact/{id}"')]
  function DeleteContact([kbmMW_Rest('value:"{id}"')] const AID:string):boolean;
 end;

 

What happens behind the scenes is that kbmMW automatically define resource names for the functions like this: MyREST..AddContect, MyREST..GetContacts etc.

Notice the extra dot! If we had defined the service to have a version, when we created it, that would be put between the dots.

As you can see, the resource name is just a string, and you can define all the resources you want to yourself, but know that if you use kbmMW smart services, it will automatically define resource names in the above format.

kbmMW will also automatically ask the authorization manager to validate that it is allowed to use a resource, upon a call from any client.

You can choose to make finer grained authorization by manually calling the authorization manager for validation of a call like this:

var
  res:TkbmMWAuthorizationStatus;
  sMessage:string;
begin
...
  res:=AuthorizationManager1.IsAuthorized(logintoken, 'YOURRESOURCENAME', sMessage);

res can have the value of mwasAuthorized, mwasNotAuthorized or mwasConstrained.

mwasConstained means that the authorization might be given under different circumstances (different time on day or similar). The returned sMessage may explain in more detail what was the reason that the access was denied.

In a kbmMW smart service, you can get the login token (logintoken) as an argument to the method like this:

 [kbmMW_Auth('role:[READER], grant:true')]
 [kbmMW_Rest('method:get, path:"someCall"')]
 function SomeCall([kbmMW_Arg(mwatToken)] const AToken:string):boolean;

When the SomeCall method is called, its AToken argument contains the logintoken.

You can also access the services ClientIdentity.Token property instead from within your methods if you do not want the token to be part of the argument list of your method call.

Now your REST server is protected by SSL and calls to it’s functionality limited by login.

There are many more features in the authorization manager, which I have not explained here, but visit our site at http://www.components4developers.com, and look for the kbmMW documentations section for whitepapers.

If you like this, please share the word about kbmMW wherever you can and feel free to link, like, share and copy the posts of this blog to where you find they could be useful.

 

 

REST easy with kbmMW #3 – SSL

I have in the former two “REST easy with kbmMW” articles shown, how to make a REST server with kbmMW, and how to use that REST server to easily return and store data from/to a database all in less than 30 lines of real code.

This blog post will center around how to ensure that communication with the server stays protected using SSL (Secure Socket Layer). In other words, how to make the REST server talk HTTPS rather than HTTP.

There are multiple ways to secure a kbmMW based application server with SSL, but I will focus on one simple way to do it using OpenSSL.

First we should create a certificate we can use. SSL certificates can be purchased from various places where they sell official certificates, or you can create one that is self signed. A self signed certificate is generally as secure as anything else, but it is not automatically trusted by other servers, which may flag your certificate as unsafe.

For inhouse use however, a self signed certificate is usually fine.

There are many places on the internet explaining the procedure of how to create SSL certificates using OpenSSL. You can click here for one of them.

After you have gotten access to either a bought or a homemade certificate, we can continue integrating it with the REST server.

Add a TIdServerIOHandlerSSLOpenSSL component to the main form (Unit7).

2017-05-21 22_13_49-Project6 - RAD Studio 10.1 Berlin - Unit7.png

You will need to set it’s SSLOptions properties like this:

  • SSLOptions.Mode must be sslmServer
  • Of the supported SSLOptions.SSLVersions I will suggest enabling only sslvTLSv1_2

Leave the remaining properties as is at the moment.

Now double click the OnGetPassword event handler of the IdServerIOHandlerSSLOpenSSL1 component to write some code in an event handler.

procedure TForm7.IdServerIOHandlerSSLOpenSSL1GetPassword(var Password: string);
begin
 Password:='yourCertificatePassword';
end;

The code going in the event should simply return the password you used when you created the private part of the certificate. It is required by OpenSSL to have access to this, to be able to use your private key.

Despite the above example, I would suggest you, not to hardcode the password inside your application, but rather read it from an external configuration file, of security reasons, in case your REST server executable got leaked elsewhere.

But for the current sample, with a homemade sample certificate, we can do with the hardcoded password.

Next we need to tell the kbmMW server side transport to let the OpenSSL code handle the main communication of our data. One part of that is to write an event handler for the OnConnect event of the kbmMWTCPIPIndyServerTransport1 component.

procedure TForm7.kbmMWTCPIPIndyServerTransport1Connect(AContext: TIdContext);
begin
  if AContext.Connection.IOHandler is TIdSSLIOHandlerSocketBase then
     TIdSSLIOHandlerSocketBase(AContext.Connection.IOHandler).
     PassThrough:=false;
end;

To make the compiler happy, we also need to add IdContext to the interface sections uses clause.

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, kbmMWCustomTransport, kbmMWServer,
 kbmMWTCPIPIndyServerTransport, kbmMWRESTTransStream,
 kbmMWCustomConnectionPool, kbmMWCustomSQLMetaData, kbmMWSQLiteMetaData,
 kbmMWSQLite, kbmMWORM, IdBaseComponent, IdComponent, IdServerIOHandler, IdSSL,
 IdSSLOpenSSL, IdContext;

And finally we need to link the SSL component to the server transport, and make the certificate files available to OpenSSL.

We do that by writing the following piece of code, for example in the OnCreate event handler of the main form (containing the kbmMW Indy server transport).

procedure TForm7.FormCreate(Sender: TObject);
begin
 ORM:=TkbmMWORM.Create(kbmMWSQLiteConnectionPool1);
 ORM.CreateTable(TContact);

 // Make sure that the server is now listening on port 443 which is 
 // the default port for HTTPS communication.
 kbmMWTCPIPIndyServerTransport1.Bindings.Items[0].Port:=443;
 IdServerIOHandlerSSLOpenSSL1.SSLOptions.CertFile:='YourCertificateFile.cer';
 IdServerIOHandlerSSLOpenSSL1.SSLOptions.KeyFile:='YourPrivateKeyFile.key';

 // Optional root certificate file if purchased certificate or empty if self signed.
 IdServerIOHandlerSSLOpenSSL1.SSLOptions.RootCertFile:='';
 kbmMWTCPIPIndyServerTransport1.IdTCPServer.IOHandler:=IdServerIOHandlerSSLOpenSSL1;

 kbmMWServer1.AutoRegisterServices;
 kbmMWServer1.Active:=true;
end;

Make sure that the files YourCertificateFile.cer and YourPrivateKeyFile.key is available to the REST executable when it runs, but also make sure that they are not accessible for download for anyone else. It’s of high importance that those files (along with your private key password) is kept a secret for anybody else.

As you may notice, we change the port number for the first binding from 80 to 443, since we want to support the standard HTTPS port. You may also notice that it is possible to provide a Root certificate file. The Root certificate file typically contains a chain of public certificates that can be used by OpenSSL and browsers to verify that your own certificate is a valid and trusted certificate generated by the entity from which you have the root certificate.

Self signed certificates usually do not need any root certificate files.

Now your REST server is ready serving clients securely over SSL.

REST easy with kbmMW #2 – Database

Building on the “REST easy with kbmMW #1” article, I will now show one way to interact with data from a database.

kbmMW supports multiple ways to access databases, ranging from more complex to use but with absolutely fastest performance, to very easy to use with very good performance.

The good thing is that you can pick and choose the way you want to use, depending on the scenario. In 99.99% of all cases, the very easy way most likely will be the preferred way. In those very few scenarios where you really need to get the highest reachable performance out of your hardware, you may want to go a less abstracted route, which you can do fully supported by kbmMW.

But as the easy way is the preferred way, this is what I will show now.

Our previous REST sample only displayed Hello world in a number of different ways.

It would be more fun to create a contact management REST server as it better resembles typical use cases for REST servers.

First thing is to make the server understand databases. We do that by opening the primary form (Unit7 in our previous blogpost), and adding one of each of these components:

  • TkbmSQLiteConnectionPool
  • TkbmMWSQLMetaData

Doing that, your form will look something similar to this.

2017-05-20 19_21_16-Project6 - RAD Studio 10.1 Berlin - Unit7 [Built].png

Then set the Metadata property of the kbmMWSQLiteConnectionPool1 component to kbmMWSQLiteMetaData1.

And set the Database property of the kbmMWSQLiteConnectionPool1 component to the string ‘.\test.db3′.

Set mwsloAutoCreateDB in the SQLiteOptions property of the kbmMWSQLiteConnectionPool1.

And if the Active property of kbmMWSQLiteConnectionPool1 is true, set it to false.

What we have done, is prepared the server to work with a SQLite database. We do need to make sure that a reasonably new sqlite3.dll (if on Windows) is to be found in the same directory as the executable of this project. You can download SQLite from http://www.sqlite.org

We have also told kbmMW that we want kbmMW to auto create the referenced database, if it do not exist.

Save the project. It will make sure Delphi updates referenced units.

Right now we already have access to the kbmMW’s fast database access methods (the 0.01% use case mentioned above). But as I want to demonstrate the easy database access route, we should do add a little bit of code to the Unit7 main form.

Now we will need to put a single line of code into the form’s OnDestroy event, let us do that now. Double click the OnDestroy event of the form in the object inspector, and we will be brought to the source code. Add the following line:

     ORM.Free;

In the already existing OnCreate event of the form, we also need to add a line of code:

     ORM:=TkbmMWORM.Create(kbmMWSQLiteConnectionPool1);

In the form’s public interface section we need to add a new field:

    ORM:TkbmMWORM;

And finally in the uses clause in the interface section we must add the kbmMWORM unit.

The source of your main server form should now look similar to this. The code we have just updated is shown in bold.

unit Unit7;

interface

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, kbmMWCustomTransport, kbmMWServer,
 kbmMWTCPIPIndyServerTransport, kbmMWRESTTransStream,
 kbmMWCustomConnectionPool, kbmMWCustomSQLMetaData, kbmMWSQLiteMetaData,
 kbmMWSQLite, kbmMWORM;

type
 TForm7 = class(TForm)
 kbmMWServer1: TkbmMWServer;
 kbmMWTCPIPIndyServerTransport1: TkbmMWTCPIPIndyServerTransport;
 kbmMWSQLiteConnectionPool1: TkbmMWSQLiteConnectionPool;
 kbmMWSQLiteMetaData1: TkbmMWSQLiteMetaData;
 procedure FormCreate(Sender: TObject);
 procedure FormDestroy(Sender: TObject);
 private
 { Private declarations }
 public
 { Public declarations }
 ORM:TkbmMWORM;
 end;

var
 Form7: TForm7;

implementation

{$R *.dfm}

procedure TForm7.FormCreate(Sender: TObject);
begin
 ORM:=TkbmMWORM.Create(kbmMWSQLiteConnectionPool1);
 kbmMWServer1.AutoRegisterServices;
 kbmMWServer1.Active:=true;
end;

procedure TForm7.FormDestroy(Sender: TObject);
begin
 ORM.Free;
end;

end.

Next thing to think about is what are we going to store in the database? As it’s a contact management system, we might want to store contact name, address, zip code, city and a comment.

For some contacts we may not know the address, or city, or we may not have specified a comment. So our contact storage must be able to differentiate between data and no data for any of the stored values. Fortunately that is how most SQL type databases operate. They understand a state of NULL for each field defined in them. That state can be checked to see if the field contains a value or not. An empty string is considered a value.

So let’s make a Delphi object that can contain this information.

Create a new unit by clicking File – New – Unit in Delphi.

This gives us an empty source only unit. The intention with it, is that it will hold the definition of our contact object.

The basic TContact class could look like this

 TContact = class
 private
  FID:kbmMWNullable<string>;
  FName:kbmMWNullable<string>;
  FAddress:kbmMWNullable<string>;
  FZipCode:kbmMWNullable<integer>;
  FCity:kbmMWNullable<string>;
  FComments:kbmMWNullable<string>;
 public
  property ID:kbmMWNullable<string> read FID write FID;
  property Name:kbmMWNullable<string> read FName write FName;
  property Address:kbmMWNullable<string> read FAddress write FAddress;
  property ZipCode:kbmMWNullable<integer> read FZipCode write FZipCode;
  property City:kbmMWNullable<string> read FCity write FCity;
  property Comments:kbmMWNullable<string> read FComments write FComments;
 end;

You will notice that there is an additional field named FID (with its property description). The idea is that we want to be able to identify a specific contact uniquely later on, without having to use the name or other information type fields (since the contents of those could change by the end user).

There are multiple ways to define a unique identifier. Some may have heard about auto incrementing fields. Some may have heard about sequencers or generators (which is sort of the same as auto incrementing fields, just in a different packing), and then some may have heard about using GUID‘s (Globally Unique IDentifiers) which often are represented as 38 character strings.

I personally prefer using GUID‘s for unique identifiers, because it allows me to import the database in another system, and even to integrate data across different database systems, without risking accidental renumbering of auto incrementing identifiers.

Performance wise GUID‘s are slightly slower and takes up additional space in a database, but that is usually only an issue to consider if you know you will have tens of millions of records in a table. If that’s not the case I recommend using GUID’s. I will show in a moment how.

But first I will talk about the other weird thing in the object… the kbmMWNullable generic type.

It allows for a field variable to contain both the value (for ‘name’, a string), and an indication about if the variable is null or not null.  In addition it also keeps track of if the value in the field has been modified or not, which can be very practical to know about  when the object is to be used to magically make the contents of the object be part of the database.

In fact, every time you have data in an object you would like to put into a database, wrap its fields with kbmMWNullable. The only exception is if your field is of type TkbmMWDataTime (which is a kbmMW TDateTime like type that also understands timezones and more), since it by itself is null and modification aware.

Back to the GUID. We want the ID property to be used as the primary identification for our contact. So let’s tell kbmMW that by adding an attribute to it.

 [kbmMW_Field('name:id, primary:true, generator:shortGuid',ftString,40)]
 property ID:kbmMWNullable<string> read FID write FID;

We have told kbmMW to handle this property as a field named ‘id’ in a data storage (like our database) and that should be stored as the datatype ftString with the size of max 40 characters. In addition the field is to be considered the primary point of access to data in the database for the TContact type information.

We have also told kbmMW that we want the actual contents of this field to be automatically generated using the shortGUID generator which produces string GUID’s without dashes and curly braces.

Now let us create similar attributes for the remaining properties, so kbmMW knows what to do about them in relation to a database.

And finally we might also want to tell kbmMW that this TContact object is to be stored in a container (usually a table) with a specific name in the database.

As in blog post #1 we also need to register the class to kbmMW. The registration can be done any time, as long as it is before first time the object is to be used by kbmMW. Typically registration is put into the initialization section of the unit. And a couple of units, DB, kbmMWNullable, kbmMWRTTI and kbmMWORM must be added to the uses clause. Now we have defined the skeleton around what a contact is, and we have a place to put the information about a single contact. But what about multiple contacts? That’s easy.. we consider multiple contacts as being a list of contacts. In Delphi code terms using generics: TObjectList<TContact>

This object list also needs to be registered with kbmMW and the Delphi generics list unit (System.Generics.Collections) must be added. The resulting unit will look like this:

unit Unit9;

interface

uses
 DB,
 System.Generics.Collections,
 kbmMWRTTI,
 kbmMWORM,
 kbmMWNullable;

type

[kbmMW_Table('name:contact')]
TContact = class
private
 FID:kbmMWNullable<string>;
 FName:kbmMWNullable<string>;
 FAddress:kbmMWNullable<string>;
 FZipCode:kbmMWNullable<integer>;
 FCity:kbmMWNullable<string>;
 FComments:kbmMWNullable<string>;
public
 [kbmMW_Field('primary:true, generator:shortGuid',ftString,40)]
 property ID:kbmMWNullable<string> read FID write FID;

 [kbmMW_Field('name:name',ftString,50)] 
 property Name:kbmMWNullable<string> read FName write FName;

 [kbmMW_Field('name:address',ftString,80)]
 property Address:kbmMWNullable<string> read FAddress write FAddress;

 [kbmMW_Field('name:zipCode',ftInteger)]
 property ZipCode:kbmMWNullable<integer> read FZipCode write FZipCode;

 [kbmMW_Field('name:city',ftString,50)]
 property City:kbmMWNullable<string> read FCity write FCity;

 [kbmMW_Field('name:comments',ftMemo)]
 property Comments:kbmMWNullable<string> read FComments write FComments;
end;

implementation

initialization
 kbmMWRegisterKnownClasses([TContact,TObjectList<TContact>]);
end.

 

So we now have the understanding of a single contact and a list of contacts. That should cover our data type needs for now.

Save all.

Next we need to establish a place in the SQLite database where this data can be stored. This is fortunately very easy to do. Open up your main form, and add this new data unit (Unit9) to the uses clause of the main form’s implementation section like this:

...
var
 Form7: TForm7;

implementation

uses Unit9;
...

And a good place to tell kbmMW where to store TContact type data, could be in the form’s OnCreate event.

procedure TForm7.FormCreate(Sender: TObject);
begin
 ORM:=TkbmMWORM.Create(kbmMWSQLiteConnectionPool1);
 ORM.CreateTable(TContact);
 kbmMWServer1.AutoRegisterServices;
 kbmMWServer1.Active:=true;
end;

kbmMW’s easy to use ORM (Object Relational Manager), automatically detects if the database already contains TContact type data or not. If it does not, kbmMW prepares the database to hold such information.

If we would run the application now, a file called test.db3 is created and using a SQLite database exploration tool like kbmMWSQLiteMan (which can be downloaded for free after registering on our portal at https://portal.components4developers.com), you can see that the database has been prepared with an empty table.

2017-05-20 20_48_19-kbmSQLiteMan v.1.6.3.2.png

Now we can start to write some REST functionality to access and manipulate the contacts data.

Open Unit8 (the kbmMW smart service).

We will add functions to return all contacts known to the system, to add a contact only providing name, to add a contact providing name, address, zipcode and city, and to delete a contact by it’s id.

The service will then look like this:

 

 [kbmMW_Service('name:MyREST, flags:[listed]')]
 [kbmMW_Rest('path:/MyREST')]
 TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
 public
   [kbmMW_Rest('method:get, path:helloworld, anonymousResult:true')]
   [kbmMW_Method]
   function HelloWorld:TMyResult;

   [kbmMW_Rest('method:get, path:contacts, anonymousResult:true')]
   function GetContacts:TObjectList<TContact>;

   [kbmMW_Rest('method:put, path:addcontact')]
   function AddContact(
     [kbmMW_Rest('value:"{$name}"')] const AName:string;
     [kbmMW_Rest('value:"{$address}"')] const AAddress:string;
     [kbmMW_Rest('value:"{$zipcode}"')] const AZipCode:string;
     [kbmMW_Rest('value:"{$city}"')] const ACity:string):string; overload;

   [kbmMW_Rest('method:get, path:"addcontact/{name}"')]
   function AddContact([kbmMW_Rest('value:"{name}"')] const AName:string):string; overload;

   [kbmMW_Rest('method:delete, path:"contact/{id}"')]
   function DeleteContact([kbmMW_Rest('value:"{id}"')] const AID:string):boolean;
 end;

You can see a number of new functions.

  • GetContacts method which will return a TObjectList of TContact. We have told kbmMW that we want it to be called when people use this URL to perform a HTTP GET request: http://localhost/MyREST/contacts
    The result will be a JSON array of contact information.
  • AddContact method which will take a name, address, zipcode and city and return a string (the id of the newly created contact). It will be activated the moment someone makes an HTTP PUT request on http://localhost/MyREST/addcontact
    The caller should include HTML form fields named name, address, zipcode and city. kbmMW will automatically attempt to pair the provided formfields with the arguments for the AddContacts method according to the mapping shown.
  • AddContact method which will take a name only, and return a string (the id of the newly created contact). It will be called when someone makes an HTTP GET request on http://localhost/MyREST/addcontact/somename
    The somename part should be the name of the contact to add.
  • DeleteContact method which will take an id, and return a boolean true/false for if the operation succeeded. It will be called when someone makes an HTTP DELETE request on http://localhost/MyREST/contact/someid
    The someid part should be the id of the contact to delete.

The implementation of these functions is very simple. Make sure that Unit7 (the main form unit) is added to the uses clause of the interface section of Unit8 (the kbmMW smart service module), and add the following code:

function TkbmMWCustomSmartService8.GetContacts:TObjectList<TContact>;
begin
 Result:=Form7.ORM.QueryList<TContact>;
end;

function TkbmMWCustomSmartService8.AddContact(const AName:string;
 const AAddress:string;
 const AZipCode:string;
 const ACity:string):string;
var
 c:TContact;
begin
 c:=TContact.Create;
 c.Name:=AName;
 c.Address:=AAddress;
 c.ZipCode:=AZipCode;
 c.City:=ACity;
 Form7.ORM.Persist(c);
 Result:=c.ID;
end;

function TkbmMWCustomSmartService8.AddContact(const AName:string):string;
var
 c:TContact;
begin
 c:=TContact.Create;
 c.Name:=AName;
 Form7.ORM.Persist(c);
 Result:=c.ID;
end;

function TkbmMWCustomSmartService8.DeleteContact(const AID:string):boolean;
begin
 Form7.ORM.Delete<TContact>([AID]);
end;

That is really all that is needed to enable returning a list of contacts, adding new contacts and deleting a contact. kbmMW’s ORM makes all the work for us automatically.

Basically a REST enabled contact manager in only 30 lines of actual code and a definition of a TContact class.

This obviously can be expanded on in many ways, but I will leave that up to the reader.

Feel free to share, retweet, repost, comment and like this post! 🙂

 

 

REST easy with kbmMW #1

REST servers are very easy to make using kbmMW.

First we make a server application (or service… it’s up to you).

In this case we will add a simple form both providing a GUI and a place for our kbmMW components.

In Delphi click File – New – VCL Forms application

Add one of each of the following kbmMW components to the form:

  • TkbmMWServer
  • TkbmMWTCPIPIndyServerTransport

2017-05-20 14_50_54-Project6 - RAD Studio 10.1 Berlin - Unit7.png

Set the Server property of kbmMWTCPIPIndyServerTransport1 to kbmMWServer1.

Double click the Bindings property of kbmMWTCPIPIndyServerTransport1 to open its editor. Add a binding for 0.0.0.0 port 80, which is the default HTTP server port. You can choose any other binding you want, but make sure to tell your REST users which port to access.2017-05-20 14_53_34-Project6 - RAD Studio 10.1 Berlin - Unit7.png

Set the Streamformat property of kbmMWTCPIPIndyTransport1 to REST.2017-05-20 14_56_15-Project6 - RAD Studio 10.1 Berlin - Unit7.png

Save your project. Saving it will prompt Delphi to update your uses section with required units.

Double click on the form, to create a form OnCreate event handler.

Enter two lines of code so it looks like this:

procedure TForm7.FormCreate(Sender: TObject);
begin
 kbmMWServer1.AutoRegisterServices;
 kbmMWServer1.Active:=true;
end;

Locate the interface section’s uses clause and add an additional unit kbmMWRESTTransStream.

Save again.

Now your unit code should look similar to this:

unit Unit7;

interface

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, kbmMWCustomTransport, kbmMWServer,
 kbmMWTCPIPIndyServerTransport, kbmMWRESTTransStream;

type
 TForm7 = class(TForm)
 kbmMWServer1: TkbmMWServer;
 kbmMWTCPIPIndyServerTransport1: TkbmMWTCPIPIndyServerTransport;
 procedure FormCreate(Sender: TObject);
 private
 { Private declarations }
 public
 { Public declarations }
 end;

var
 Form7: TForm7;

implementation

{$R *.dfm}

procedure TForm7.FormCreate(Sender: TObject);
begin
 kbmMWServer1.AutoRegisterServices;
 kbmMWServer1.Active:=true;
end;

end.

Basically we now have the foundation for a REST capable web server.

Let’s add some functionality that can be called from any REST client.

In Delphi, Click FileNewOtherComponents4Developers Wizards and select the kbmMW Service Wizard. Click OK.

2017-05-20 15_09_18-Project6 - RAD Studio 10.1 Berlin - Unit7.png

Before continuing to select the type of kbmMW service we will add, we need to decide what type of REST server we want to create. It can be a pure REST server, which only serves data from your own code, or it can be a regular web server, which will also be able to serve data from files on disk, like html templates, images, CSS files etc.

For our purpose we just want to make a pure REST server, so we select
Smart service/kbmMW_1.0.

If you wanted it to be able to serve files from disk, and even proxy requests on to other FastCGI compatible servers (like PHP etc) you would have chosen HTTP Smart service.

2017-05-20 15_13_56-kbmMW service wizard.png

Click the funny looking next button. Type in the default name your REST service should be known as. In this sample, I’ve called it MyREST.

2017-05-20 15_15_16-Project6 - RAD Studio 10.1 Berlin - Unit7.png

Click next until you get to this page, then click the green checkmark button

2017-05-20 15_16_42-kbmMW service wizard.png

Now an almost empty service has been generated for you.

On the surface it looks like a regular TDataModule, and as such can contain any component that you can put on a TDataModule. But right now we are more interested in its code. Press F12 to switch to code view.

Browse past the explanatory remarks at the top, until you get to the actual code.

type

[kbmMW_Service('name:MyREST, flags:[listed]')]
[kbmMW_Rest('path:/MyREST')]
 // Access to the service can be limited using the [kbmMW_Auth..] attribute.
 // [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]

TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
 private
 { Private declarations }
 protected
 { Protected declarations }
 public
 { Public declarations }
 // HelloWorld function callable from both a regular client,
 // due to the optional [kbmMW_Method] attribute,
 // and from a REST client due to the optional [kbmMW_Rest] attribute.
 // The access path to the function from a REST client (like a browser)+
 // is in this case relative to the services path.
 // In this example: http://.../MyREST/helloworld
 // Access to the function can be limited using the [kbmMW_Auth..] attribute.
 // [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]
 [kbmMW_Rest('method:get, path:helloworld')]
 [kbmMW_Method]
 function HelloWorld:string;
 end;

implementation

uses kbmMWExceptions;

{$R *.dfm}


// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:string;
begin
 Result:='Hello world';
end;

The interesting bits are shown above in bold.

If you compile and run your application now, you have a REST only capable webserver which have one function… HelloWorld taking no arguments, and that returns a string.

Open up your favorite web browser and lets test the function by typing this in the address field:

http://localhost/MyREST/helloworld

Make sure that case is correct, since the HTTP standard describes that the URL part of the address must be case sensitive. If you would write http://localhost/MyREST/HelloWorld instead you would be told that the request is invalid.

This is all nice… but my REST client expect to receive a JSON object, not just simple text.

Ok.. I’ll show 3 ways to do that… the very manual way, the semi automated way and the fully automated way.

The manual way. Change the HelloWorld function to look like this:

function TkbmMWCustomSmartService8.HelloWorld:string;
begin
 Result:='{''result'':''Hello world''}';
end;

The REST client will receive an anonymous object with a property called result, containing “Hello world”.

The semi automated way:

uses kbmMWExceptions
 ,kbmMWObjectNotation
 ,kbmMWJSON;

{$R *.dfm}


// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:string;
var
 o:TkbmMWONObject;
 jsonstreamer:TkbmMWJSONStreamer;
begin
 o:=TkbmMWONObject.Create;
 jsonstreamer:=TkbmMWJSONStreamer.Create;

 o.AsString['result']:='Hello world';
 Result:=jsonstreamer.SaveToUTF16String(o);

 jsonstreamer.Free;
 o.Free;
end;

This allows you to create complex JSON documents pretty easily. The cool part is that since we use kbmMW’s object notation framework, we could have chosen to stream it as XML or YAML or BSON or MessagePack instead by simply instantiating the appropriate streamer.

The automated way:

type

TMyResult = class
private
 FResult:string;
public
 property Result:string read FResult write FResult;
end;

 [kbmMW_Service('name:MyREST, flags:[listed]')]
 [kbmMW_Rest('path:/MyREST')]
 // Access to the service can be limited using the [kbmMW_Auth..] attribute.
 // [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]

TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
 private
 [kbmMW_Rest('method:get, path:helloworld, anonymousResult:true')]
 [kbmMW_Method]
 function HelloWorld:TMyResult;
 end;

implementation

uses kbmMWExceptions;

{$R *.dfm}

// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:TMyResult;
begin
 Result:=TMyResult.Create;
 Result.Result:='Hello world';
end;

initialization
 TkbmMWRTTI.EnableRTTI(TkbmMWCustomSmartService8);
 kbmMWRegisterKnownClasses([TMyResult]);
end.

The automated way simply means returning an object with the desired information. kbmMW will automatically convert the object to JSON (because we are using the REST streamformat).

To make sure that kbmMW knows about the object type, we register it via the kbmMWRegisterKnownClasses. If we didn’t, kbmMW would complain that it do not know about the object.

Do not worry about the TMyResult instance being leaked. kbmMW will automatically free it when it goes out of scope. If you specifically do not want the returned object to be freed by kbmMW, you can tell so by including freeResult:false in the kbmMW_Rest attribute for the HelloWorld method.

Also notice that the kbmMW_Rest attribute now includes anonymousResult:true.

This tells kbmMW that we want the resulting JSON to be anonymous. If we didn’t include that attribute setting, the result would have looked like this:

{"TMyResult":{"Result":"Hello world"}}

Which is not necessarily wrong, but different.

There are lots of control options of how the object should be streamed by setting various attributes on it. One can for example choose that the Result property should be returned under a different name etc.

kbmMW also understands returning TkbmMemTable instances, arrays and many other types of information, so it is really easy to REST’ify your kbmMW business functionality with almost no lines of additional code.

As a final comment, since the HelloWorld method is also tagged with the attribute [kbmMW_Method], it is also callable by native kbmMW clients.

Feel free to share, comment and like this post 🙂

 

Getting a free kbmMemTable and kbmMW

How do I get a free kbmMemTable or kbmMW?

We provide a free license which can also be used for commercial applications. What you should look for is kbmMW CodeGear Edition.

The installer of kbmMW CodeGear Edition includes kbmMemTable CodeGear Edition, which thus installs automatically along with kbmMW CodeGear Edition.

Get kbmMW CodeGear Edition by logging in on https://portal.components4developers.com

If you have never logged in on our download portal before, you will need to register yourself first. We do not verify the information you provide for name etc, but please, as a courtesy to us, type in your real name and accessible email address. as a minimum.

When you have logged in, you will have direct access to all the free products we currently offer, and in all the versions we have made available.

kbmMW CodeGear Edition do not include source code, so you will have to choose a version matching the development environment you have. CodeGear Edition only supports Delphi.

Further kbmMW CodeGear Edition is updated less regular than our paid versions of kbmMemTable and kbmMW. Latest version released of CodeGear Edition will only match latest version of Delphi. Thus the older Delphi version you will want to download for, the older version of kbmMW CodeGear Edition you will need to download.

What do you get with kbmMW CodeGear Edition?

  • A complete application server framework
  • Standard TCP/IP based communication channel
  • Remote dataset support with resolving features
  • Server side support for FireDAC, DBExpress,  IBExpress and SQLite
  • Advanced logging framework
  • Native XML support
  • Native JSON support
  • ISAPI communication support
  • Support for a subset of compression libraries
  • Support for a subset of hashing methods
  • Advanced DateTime with Timezone support
  • Server and client side dataset caching
  • Advanced actor, role, resource, condition based authorization manager
  • kbmMemTable with without source, but with indexing, filtering, ordering, SQL and more support

What  do you not get with kbmMW CodeGear Edition?

  • Source
  • Latest version
  • No limitations in server and client side caching
  • No limitations in number of concurrent server service instances
  • 35+ more database adapters
  • YAML, BSON, MessagePack support
  • Loadbalancing and failover
  • Messaging
  • High quality encryption functionality including AES and many other algorithms
  • High quality hashing functionality including SHA256/512 and many other algorithms
  • High quality readable password generators
  • High quality random generator algorithms
  • High performance compression algorithms
  • C++ support
  • Smart REST support for boilerplate free code
  • Smart services and clients for boilerplate free code
  • File service and client support
  • Advanced job scheduler support
  • XSD importer support
  • Apache Message Queue Protocol support
  • Advanced debugging support
  • HTTPSys high performance transport for REST
  • Integration support with .Net, Java, Apache Flex, Adobe Flash, PHP, K&R C, OCX
  • Most complete and performant multi monitor remote desktop support
  • Boilerplate free ORM support
  • And many more things

The above features are all available in kbmMW Enterprise Edition. kbmMW Professional Edition contains a subset of them. Both kbmMW Enterprise Edition and kbmMW Professional Edition includes source.

Please check our site for detailed feature matrix.