-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
intf.OpenMasterdata.pas
582 lines (488 loc) · 16.9 KB
/
intf.OpenMasterdata.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
{
License OpenMasterdata-for-Delphi
Copyright (C) 2024 Landrix Software GmbH & Co. KG
Sven Harazim, [email protected]
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}
unit intf.OpenMasterdata;
interface
uses
System.SysUtils,System.Classes,System.Contnrs,System.Variants,System.DateUtils
,System.Generics.Collections,System.Generics.Defaults,System.SyncObjs
,System.NetEncoding,System.Net.HttpClient,System.Net.URLClient
,Vcl.StdCtrls,System.JSON,REST.Json,REST.JsonReflect, REST.Types, REST.Client
,intf.OpenMasterdata.Types
;
type
IOpenMasterdataApiClient = interface
['{425FC785-64D4-4A17-A012-49F60448EBF8}']
function GetBySupplierPid(_SupplierPid : String; _DataPackages : TOpenMasterdataAPI_DataPackages; out _Result: TOpenMasterdataAPI_Result) : Boolean;
procedure SetOAuthURL(const _URL : String);
procedure SetBySupplierPIDURL(const _URL : String);
function GetData(_Url : String; out _Result : TStream) : Boolean;
function GetConnectionName : String;
function GetCurrentAuthorizationToken : String;
function GetLastOAuthResponseContent : String;
function GetLastBySupplierPIDResponseContent : String;
function GetLastErrorMessage : String;
function GetLastErrorCode : Integer;
end;
TOpenMasterdataApiClient = class(TInterfacedObject,IOpenMasterdataApiClient)
public type
TGrantType = (omdgt_Password,omdgt_ClientCredentials);
public type
TValidateCertificatHelper = class(TObject)
procedure DoValidateCertificateEvent(const Sender: TObject;
const ARequest: TURLRequest; const Certificate: TCertificate;
var Accepted: Boolean);
end;
private
FCS : TCriticalSection;
FUsername,
FPassword,
FCustomerNumber,
FClientID,
FClientSecret,
FClientScope,
FConnectionName : String;
FGrantType : TGrantType;
FAccessToken : String;
FRefreshToken : String;
FAccessTokenValidTo : TDateTime;
//FCookie : String;
FRESTClientOAuth: TRESTClient;
FRESTClientBySupplierPID: TRESTClient;
FLastOAuthResponseContent : String;
FLastBySupplierPIDResponseContent : String;
FLastErrorMessage : String;
FLastErrorCode : Integer;
function LoggedIn: Boolean;
function Login : Boolean;
function RefreshLogin : Boolean;
public
constructor Create(_ConnectionName, _Username, _Password, _CustomerNumber, _ClientID, _ClientSecret, _ClientScope : String; _GrantType : TGrantType);
destructor Destroy; override;
public
function GetConnectionName : String;
function GetCurrentAuthorizationToken : String;
function GetLastOAuthResponseContent : String;
function GetLastBySupplierPIDResponseContent : String;
function GetLastErrorMessage : String;
function GetLastErrorCode : Integer;
procedure SetOAuthURL(const _URL : String);
procedure SetBySupplierPIDURL(const _URL : String);
function GetBySupplierPid(_SupplierPid : String; _DataPackages : TOpenMasterdataAPI_DataPackages; out _Result: TOpenMasterdataAPI_Result) : Boolean;
public
function GetData(_Url : String; out _Result : TStream) : Boolean;
public
class function GetOpenMasterdataConnection(_ConnectionName : String; out _Connection : IOpenMasterdataApiClient) : Boolean;
class function NewOpenMasterdataConnection(_ConnectionName, _Username, _Password, _CustomerNumber,_ClientID, _ClientSecret, _ClientScope : String; _GrantType : TGrantType) : IOpenMasterdataApiClient;
class function GetGrantTypeFromString(const _Val : String; _Default : TGrantType = TGrantType.omdgt_Password) : TGrantType;
end;
implementation
var
openConnections : TInterfaceList;
{ TOpenMasterdataApiClient }
class function TOpenMasterdataApiClient.GetOpenMasterdataConnection(
_ConnectionName: String;
out _Connection: IOpenMasterdataApiClient): Boolean;
var
i : Integer;
begin
Result := false;
if openConnections = nil then
openConnections := TInterfaceList.Create;
for i := 0 to openConnections.Count-1 do
if SameText(_ConnectionName,
IOpenMasterdataApiClient(openConnections[i]).GetConnectionName) then
begin
_Connection := IOpenMasterdataApiClient(openConnections[i]);
Result := true;
break;
end;
end;
class function TOpenMasterdataApiClient.NewOpenMasterdataConnection(
_ConnectionName, _Username, _Password, _CustomerNumber, _ClientID,
_ClientSecret,_ClientScope: String;
_GrantType : TGrantType): IOpenMasterdataApiClient;
begin
if openConnections = nil then
openConnections := TInterfaceList.Create;
if GetOpenMasterdataConnection(_ConnectionName,Result) then
exit;
Result := TOpenMasterdataApiClient.Create(_ConnectionName,_Username, _Password,
_CustomerNumber,_ClientID,_ClientSecret,_ClientScope,_GrantType);
openConnections.Add(Result);
end;
constructor TOpenMasterdataApiClient.Create(_ConnectionName, _Username,
_Password, _CustomerNumber, _ClientID, _ClientSecret, _ClientScope: String;
_GrantType : TGrantType);
begin
FConnectionName := _ConnectionName;
FUsername := _Username;
FPassword := _Password;
FCustomerNumber := _CustomerNumber;
FClientID := _ClientID;
FClientSecret := _ClientSecret;
FClientScope := _ClientScope;
FGrantType := _GrantType;
FCS := TCriticalSection.Create;
FRESTClientOAuth:= TRESTClient.Create(nil);
FRESTClientOAuth.Name := 'RESTClientOAuth';
FRESTClientBySupplierPID:= TRESTClient.Create(nil);
FRESTClientBySupplierPID.Name := 'RESTClientBySupplierPID';
FLastOAuthResponseContent := '';
FLastBySupplierPIDResponseContent := '';
FLastErrorMessage := '';
FLastErrorCode := 0;
FAccessToken := '';
FRefreshToken := '';
FAccessTokenValidTo := 0;
//FCookie := '';
end;
destructor TOpenMasterdataApiClient.Destroy;
begin
if Assigned(FRESTClientOAuth) then begin FRESTClientOAuth.Free; FRESTClientOAuth := nil; end;
if Assigned(FRESTClientBySupplierPID) then begin FRESTClientBySupplierPID.Free; FRESTClientBySupplierPID := nil; end;
if Assigned(FCS) then begin FCS.Free; FCS := nil; end;
inherited;
end;
function TOpenMasterdataApiClient.GetLastBySupplierPIDResponseContent: String;
begin
Result := FLastBySupplierPIDResponseContent;
end;
function TOpenMasterdataApiClient.GetLastErrorCode: Integer;
begin
Result := FLastErrorCode;
end;
function TOpenMasterdataApiClient.GetLastErrorMessage: String;
begin
Result := FLastErrorMessage;
end;
function TOpenMasterdataApiClient.GetLastOAuthResponseContent: String;
begin
Result := FLastOAuthResponseContent;
end;
function TOpenMasterdataApiClient.LoggedIn: Boolean;
begin
Result := false;
if (not FAccessToken.IsEmpty) and (now < FAccessTokenValidTo) then
begin
Result := true;
exit;
end;
if FAccessToken.IsEmpty then
Result := Login
else
if FAccessTokenValidTo <= now then
begin
if FRefreshToken.IsEmpty then
Result := Login
else
Result := RefreshLogin;
end;
end;
function TOpenMasterdataApiClient.Login: Boolean;
var
RESTResponse: TRESTResponse;
RESTRequest: TRESTRequest;
itm : TOpenMasterdataAPI_AuthResult;
begin
//https://github.com/paolo-rossi/delphi-neon
Result := false;
FLastOAuthResponseContent := '';
FLastErrorMessage := '';
FLastErrorCode := 0;
FAccessToken := '';
FRefreshToken := '';
//FCookie := '';
//TOAuth2Authenticator?
RESTResponse := TRESTResponse.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
try
RESTResponse.Name := 'RESTResponse';
RESTRequest.Name := 'RESTRequest';
RESTRequest.AssignedValues := [TCustomRESTRequest.TAssignedValue.rvConnectTimeout, TCustomRESTRequest.TAssignedValue.rvReadTimeout];
RESTRequest.Client := FRESTClientOAuth;
RESTRequest.Method := rmPOST;
case FGrantType of
omdgt_Password: RESTRequest.Params.AddItem('grant_type','password');
omdgt_ClientCredentials: RESTRequest.Params.AddItem('grant_type','client_credentials');
end;
if not FClientSecret.IsEmpty then
RESTRequest.Params.AddItem('client_secret',FClientSecret);
if not FClientScope.IsEmpty then
RESTRequest.Params.AddItem('scope',FClientScope);
RESTRequest.Params.AddItem('client_id',FClientID);
if (FUsername <> '') and (FCustomerNumber <> '') then
RESTRequest.Params.AddItem('username',FUsername+#9+FCustomerNumber)
else
if (FCustomerNumber <> '') then
RESTRequest.Params.AddItem('username',FCustomerNumber)
else
RESTRequest.Params.AddItem('username',FUsername);
RESTRequest.Params.AddItem('password',FPassword);
RESTRequest.Response := RESTResponse;
RESTRequest.Execute;
if not RESTResponse.Status.SuccessOK_200 then
begin
FLastErrorMessage := RESTResponse.StatusText;
FLastErrorCode := RESTResponse.StatusCode;
exit;
end;
FLastOAuthResponseContent := RESTResponse.Content;
itm := TOpenMasterdataAPI_AuthResult.Create;
FAccessTokenValidTo := now;
try
try
itm.LoadFromJson(RESTResponse.Content);
if itm.access_token.IsEmpty then
exit;
FAccessToken := itm.access_token;
FRefreshToken := itm.refresh_token;
FAccessTokenValidTo := IncSecond(FAccessTokenValidTo,itm.expires_in-30);
//if RESTResponse.Cookies.Count > 0 then
// FCookie := RESTResponse.Cookies[0].GetServerCookie;
Result := true;
except
on E:Exception do
begin
FLastErrorMessage := E.ClassName+' '+e.Message;
exit;
end;
end;
finally
itm.Free;
end;
finally
RESTRequest.Free;
RESTResponse.Free;
end;
end;
function TOpenMasterdataApiClient.RefreshLogin: Boolean;
var
RESTResponse: TRESTResponse;
RESTRequest: TRESTRequest;
itm : TOpenMasterdataAPI_AuthResult;
begin
//https://github.com/paolo-rossi/delphi-neon
Result := false;
FLastOAuthResponseContent := '';
FLastErrorMessage := '';
FLastErrorCode := 0;
FAccessToken := '';
//FCookie := '';
if FRefreshToken.IsEmpty then
exit;
RESTResponse := TRESTResponse.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
try
RESTResponse.Name := 'RESTResponse';
RESTRequest.Name := 'RESTRequest';
RESTRequest.AssignedValues := [TCustomRESTRequest.TAssignedValue.rvConnectTimeout, TCustomRESTRequest.TAssignedValue.rvReadTimeout];
RESTRequest.Client := FRESTClientOAuth;
RESTRequest.Params.AddItem('grant_type','refresh_token');
RESTRequest.Params.AddItem('client_id',FClientID);
RESTRequest.Params.AddItem('refresh_token',FRefreshToken);
RESTRequest.Response := RESTResponse;
RESTRequest.Execute;
if not RESTResponse.Status.SuccessOK_200 then
begin
FLastErrorMessage := RESTResponse.StatusText;
FLastErrorCode := RESTResponse.StatusCode;
exit;
end;
FLastOAuthResponseContent := RESTResponse.Content;
itm := TOpenMasterdataAPI_AuthResult.Create;
FAccessTokenValidTo := now;
try
try
itm.LoadFromJson(RESTResponse.Content);
if itm.access_token.IsEmpty or itm.refresh_token.IsEmpty then
exit;
FAccessToken := itm.access_token;
FRefreshToken := itm.refresh_token;
FAccessTokenValidTo := IncSecond(FAccessTokenValidTo,itm.expires_in-30);
//if RESTResponse.Cookies.Count > 0 then
// FCookie := RESTResponse.Cookies[0].GetServerCookie;
Result := true;
except
on E:Exception do
begin
FLastErrorMessage := E.ClassName+' '+e.Message;
exit;
end;
end;
finally
itm.Free;
end;
finally
RESTRequest.Free;
RESTResponse.Free;
end;
end;
function TOpenMasterdataApiClient.GetBySupplierPid(_SupplierPid: String;
_DataPackages: TOpenMasterdataAPI_DataPackages;
out _Result: TOpenMasterdataAPI_Result): Boolean;
var
RESTResponse: TRESTResponse;
RESTRequest: TRESTRequest;
begin
Result := false;
FCS.Acquire;
try
if not LoggedIn then
exit;
FLastBySupplierPIDResponseContent := '';
FLastErrorMessage := '';
FLastErrorCode := 0;
if _SupplierPid.IsEmpty then
exit;
if _DataPackages = [] then
exit;
RESTResponse := TRESTResponse.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
try
RESTResponse.Name := 'RESTResponse';
RESTRequest.Name := 'RESTRequest';
RESTRequest.AssignedValues := [TCustomRESTRequest.TAssignedValue.rvConnectTimeout, TCustomRESTRequest.TAssignedValue.rvReadTimeout];
RESTRequest.Client := FRESTClientBySupplierPID;
RESTRequest.AddAuthParameter('Authorization','Bearer ' + FAccessToken,TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);
//if FCookie <> '' then
// RESTRequest.AddAuthParameter('Cookie',FCookie,TRESTRequestParameterKind.pkCOOKIE, [TRESTRequestParameterOption.poDoNotEncode]);
RESTRequest.Method := rmGET;
//RESTRequest.URLAlreadyEncoded := true;
RESTRequest.AddParameter('supplierPid',TNetEncoding.URL.Encode(_SupplierPid),TRESTRequestParameterKind.pkQUERY,[TRESTRequestParameterOption.poDoNotEncode]);
RESTRequest.AddParameter('datapackage',TOpenMasterdataAPI_DataPackageHelper.DataPackagesAsString(_DataPackages),TRESTRequestParameterKind.pkQUERY,[TRESTRequestParameterOption.poDoNotEncode]);
RESTRequest.Response := RESTResponse;
RESTRequest.Execute;
if not RESTResponse.Status.SuccessOK_200 then
begin
FLastErrorMessage := RESTResponse.StatusText;
FLastErrorCode := RESTResponse.StatusCode;
exit;
end;
FLastBySupplierPIDResponseContent := RESTResponse.Content;
_Result := TOpenMasterdataAPI_Result.Create;
try
_Result.LoadFromJson(RESTResponse.Content);
Result := true;
except
on E:Exception do
begin
_Result.Free;
FLastErrorMessage := E.ClassName+' '+e.Message;
exit;
end;
end;
finally
RESTRequest.Free;
RESTResponse.Free;
end;
finally
FCS.Release;
end;
end;
function TOpenMasterdataApiClient.GetConnectionName: String;
begin
Result := FConnectionName;
end;
function TOpenMasterdataApiClient.GetCurrentAuthorizationToken: String;
begin
Result := FAccessToken;
end;
function TOpenMasterdataApiClient.GetData(_Url: String;
out _Result: TStream): Boolean;
var
lHttp : THTTPClient;
lVCHelper : TOpenMasterdataApiClient.TValidateCertificatHelper;
lData : TMemoryStream;
lHeaders : TNetHeaders;
begin
Result := false;
if _Url.IsEmpty then
exit;
FCS.Acquire;
try
if not LoggedIn then
exit;
FLastErrorMessage := '';
FLastErrorCode := 0;
lHttp := THTTPClient.Create;
lData := TMemoryStream.Create;
lVCHelper := TOpenMasterdataApiClient.TValidateCertificatHelper.Create;
try
lHttp.OnValidateServerCertificate := lVCHelper.DoValidateCertificateEvent;
try
lHeaders := [TNetHeader.Create('Authorization','Bearer ' + FAccessToken)];
with lHttp.Get(_URL,lData,lHeaders) do
begin
Result := StatusCode = 200;
if not Result then
lData.Free
else
_Result := lData;
end;
except
on E:Exception do
begin
FLastErrorMessage := E.ClassName+' '+e.Message;
end;
end;
finally
lVCHelper.Free;
lHttp.Free;
end;
finally
FCS.Release;
end;
end;
class function TOpenMasterdataApiClient.GetGrantTypeFromString(
const _Val: String; _Default: TGrantType): TGrantType;
begin
if SameText(_Val,'client_credentials') then
Result := TOpenMasterdataApiClient.TGrantType.omdgt_ClientCredentials
else
if SameText(_Val,'password') then
Result := TOpenMasterdataApiClient.TGrantType.omdgt_Password
else
Result := _Default;
end;
procedure TOpenMasterdataApiClient.SetBySupplierPIDURL(
const _URL : String);
begin
FRESTClientBySupplierPID.BaseURL := _URL;
FRESTClientBySupplierPID.Accept := 'application/json';
FRESTClientBySupplierPID.AcceptCharSet := 'UTF-8';
FRESTClientBySupplierPID.ContentType := 'application/json';
FRESTClientBySupplierPID.HandleRedirects := true;
end;
procedure TOpenMasterdataApiClient.SetOAuthURL(const _URL : String);
begin
FRESTClientOAuth.BaseURL := _URL;
end;
{ TOpenMasterdataApiClient.TValidateCertificatHelper }
procedure TOpenMasterdataApiClient.TValidateCertificatHelper.DoValidateCertificateEvent(
const Sender: TObject; const ARequest: TURLRequest;
const Certificate: TCertificate; var Accepted: Boolean);
begin
Accepted := true;
end;
initialization
openConnections := nil;
finalization
if Assigned(openConnections) then begin openConnections.Free; openConnections := nil; end;
end.