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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
|
/*
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
* Copyright (C) 2019-2020, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.policy.drools.protocol.coders;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.onap.policy.drools.controller.DroolsController;
import org.onap.policy.drools.controller.DroolsControllerConstants;
import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This protocol Coder that does its best attempt to decode/encode, selecting the best class and best fitted json
* parsing tools.
*/
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
abstract class GenericEventProtocolCoder {
private static final String INVALID_ARTIFACT_ID_MSG = "Invalid artifact id";
private static final String INVALID_GROUP_ID_MSG = "Invalid group id";
private static final String INVALID_TOPIC_MSG = "Invalid Topic";
private static final String UNSUPPORTED_MSG = "Unsupported";
private static final String UNSUPPORTED_EX_MSG = "Unsupported:";
private static final String MISSING_CLASS = "class must be provided";
private static final Logger logger = LoggerFactory.getLogger(GenericEventProtocolCoder.class);
/**
* Mapping topic:controller-id -> /<protocol-decoder-toolset/> where protocol-coder-toolset contains
* a gson-protocol-coder-toolset.
*/
protected final HashMap<String, ProtocolCoderToolset> coders =
new HashMap<>();
/**
* Mapping topic + classname -> Protocol Set.
*/
protected final HashMap<String, List<ProtocolCoderToolset>>
reverseCoders = new HashMap<>();
/**
* Index a new coder.
*/
public void add(EventProtocolParams eventProtocolParams) {
if (eventProtocolParams.getGroupId() == null || eventProtocolParams.getGroupId().isEmpty()) {
throw new IllegalArgumentException(INVALID_GROUP_ID_MSG);
}
if (eventProtocolParams.getArtifactId() == null || eventProtocolParams.getArtifactId().isEmpty()) {
throw new IllegalArgumentException(INVALID_ARTIFACT_ID_MSG);
}
if (eventProtocolParams.getTopic() == null || eventProtocolParams.getTopic().isEmpty()) {
throw new IllegalArgumentException(INVALID_TOPIC_MSG);
}
if (eventProtocolParams.getEventClass() == null) {
throw new IllegalArgumentException("Invalid Event Class");
}
String key = this.codersKey(eventProtocolParams.getGroupId(), eventProtocolParams.getArtifactId(),
eventProtocolParams.getTopic());
String reverseKey = this.reverseCodersKey(eventProtocolParams.getTopic(), eventProtocolParams.getEventClass());
synchronized (this) {
if (coders.containsKey(key)) {
ProtocolCoderToolset toolset = coders.get(key);
logger.info("{}: adding coders for existing {}: {}", this, key, toolset);
toolset
.addCoder(
eventProtocolParams.getEventClass(),
eventProtocolParams.getProtocolFilter(),
eventProtocolParams.getModelClassLoaderHash());
if (!reverseCoders.containsKey(reverseKey)) {
logger.info(
"{}: adding new reverse coders (multiple classes case) for {}:{}: {}",
this,
reverseKey,
key,
toolset);
List<ProtocolCoderToolset> reverseMappings =
new ArrayList<>();
reverseMappings.add(toolset);
reverseCoders.put(reverseKey, reverseMappings);
}
return;
}
var coderTools = new GsonProtocolCoderToolset(eventProtocolParams, key);
logger.info("{}: adding coders for new {}: {}", this, key, coderTools);
coders.put(key, coderTools);
addReverseCoder(coderTools, key, reverseKey);
}
}
private void addReverseCoder(GsonProtocolCoderToolset coderTools, String key, String reverseKey) {
if (reverseCoders.containsKey(reverseKey)) {
// There is another controller (different group id/artifact id/topic)
// that shares the class and the topic.
List<ProtocolCoderToolset> toolsets =
reverseCoders.get(reverseKey);
var present = false;
for (ProtocolCoderToolset parserSet : toolsets) {
// just doublecheck
present = parserSet.getControllerId().equals(key);
if (present) {
/* anomaly */
logger.error(
"{}: unexpected toolset reverse mapping found for {}:{}: {}",
this,
reverseKey,
key,
parserSet);
}
}
if (!present) {
logger.info("{}: adding coder set for {}: {} ", this, reverseKey, coderTools);
toolsets.add(coderTools);
}
} else {
List<ProtocolCoderToolset> toolsets = new ArrayList<>();
toolsets.add(coderTools);
logger.info("{}: adding toolset for reverse key {}: {}", this, reverseKey, toolsets);
reverseCoders.put(reverseKey, toolsets);
}
}
/**
* produces key for indexing toolset entries.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @return index key
*/
protected String codersKey(String groupId, String artifactId, String topic) {
return groupId + ":" + artifactId + ":" + topic;
}
/**
* produces a key for the reverse index.
*
* @param topic topic
* @param eventClass coded class
* @return reverse index key
*/
protected String reverseCodersKey(String topic, String eventClass) {
return topic + ":" + eventClass;
}
/**
* remove coder.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @throws IllegalArgumentException if invalid input
*/
public void remove(String groupId, String artifactId, String topic) {
if (groupId == null || groupId.isEmpty()) {
throw new IllegalArgumentException(INVALID_GROUP_ID_MSG);
}
if (artifactId == null || artifactId.isEmpty()) {
throw new IllegalArgumentException(INVALID_ARTIFACT_ID_MSG);
}
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(INVALID_TOPIC_MSG);
}
String key = this.codersKey(groupId, artifactId, topic);
synchronized (this) {
if (coders.containsKey(key)) {
ProtocolCoderToolset coderToolset = coders.remove(key);
logger.info("{}: removed toolset for {}: {}", this, key, coderToolset);
for (CoderFilters codeFilter : coderToolset.getCoders()) {
String className = codeFilter.getFactClass();
String reverseKey = this.reverseCodersKey(topic, className);
removeReverseCoder(key, reverseKey);
}
}
}
}
private void removeReverseCoder(String key, String reverseKey) {
if (!this.reverseCoders.containsKey(reverseKey)) {
return;
}
List<ProtocolCoderToolset> toolsets =
this.reverseCoders.get(reverseKey);
Iterator<ProtocolCoderToolset> toolsetsIter =
toolsets.iterator();
while (toolsetsIter.hasNext()) {
ProtocolCoderToolset toolset = toolsetsIter.next();
if (toolset.getControllerId().equals(key)) {
logger.info(
"{}: removed coder from toolset for {} from reverse mapping", this, reverseKey);
toolsetsIter.remove();
}
}
if (this.reverseCoders.get(reverseKey).isEmpty()) {
logger.info("{}: removing reverse mapping for {}: ", this, reverseKey);
this.reverseCoders.remove(reverseKey);
}
}
/**
* does it support coding.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @return true if its is codable
*/
public boolean isCodingSupported(String groupId, String artifactId, String topic) {
if (groupId == null || groupId.isEmpty()) {
throw new IllegalArgumentException(INVALID_GROUP_ID_MSG);
}
if (artifactId == null || artifactId.isEmpty()) {
throw new IllegalArgumentException(INVALID_ARTIFACT_ID_MSG);
}
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(INVALID_TOPIC_MSG);
}
String key = this.codersKey(groupId, artifactId, topic);
synchronized (this) {
return coders.containsKey(key);
}
}
/**
* decode a json string into an Object.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @param json json string to convert to object
* @return the decoded object
* @throws IllegalArgumentException if invalid argument is provided
* @throws UnsupportedOperationException if the operation cannot be performed
*/
public Object decode(String groupId, String artifactId, String topic, String json) {
if (!isCodingSupported(groupId, artifactId, topic)) {
throw new IllegalArgumentException(
UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic) + " for encoding");
}
String key = this.codersKey(groupId, artifactId, topic);
ProtocolCoderToolset coderTools = coders.get(key);
try {
Object event = coderTools.decode(json);
if (event != null) {
return event;
}
} catch (Exception e) {
logger.debug("{}, cannot decode {}", this, json, e);
}
throw new UnsupportedOperationException("Cannot decode with gson");
}
/**
* encode an object into a json string.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @param event object to convert to string
* @return the json string
* @throws IllegalArgumentException if invalid argument is provided
* @throws UnsupportedOperationException if the operation cannot be performed
*/
public String encode(String groupId, String artifactId, String topic, Object event) {
if (!isCodingSupported(groupId, artifactId, topic)) {
throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic));
}
if (event == null) {
throw new IllegalArgumentException("Unsupported topic:" + topic);
}
// reuse the decoder set, since there must be affinity in the model
String key = this.codersKey(groupId, artifactId, topic);
return this.encodeInternal(key, event);
}
/**
* encode an object into a json string.
*
* @param topic topic
* @param event object to convert to string
* @return the json string
* @throws IllegalArgumentException if invalid argument is provided
* @throws UnsupportedOperationException if the operation cannot be performed
*/
public String encode(String topic, Object event) {
if (event == null) {
throw new IllegalArgumentException("Invalid encoded class");
}
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException("Invalid topic");
}
String reverseKey = this.reverseCodersKey(topic, event.getClass().getName());
if (!this.reverseCoders.containsKey(reverseKey)) {
throw new IllegalArgumentException("no reverse coder has been found");
}
List<ProtocolCoderToolset> toolsets =
this.reverseCoders.get(reverseKey);
String key =
codersKey(
toolsets.get(0).getGroupId(), toolsets.get(0).getArtifactId(), topic);
return this.encodeInternal(key, event);
}
/**
* encode an object into a json string.
*
* @param topic topic
* @param encodedClass object to convert to string
* @return the json string
* @throws IllegalArgumentException if invalid argument is provided
* @throws UnsupportedOperationException if the operation cannot be performed
*/
public String encode(String topic, Object encodedClass, DroolsController droolsController) {
if (encodedClass == null) {
throw new IllegalArgumentException("Invalid encoded class");
}
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException("Invalid topic");
}
String key = codersKey(droolsController.getGroupId(), droolsController.getArtifactId(), topic);
return this.encodeInternal(key, encodedClass);
}
/**
* encode an object into a json string.
*
* @param key identifier
* @param event object to convert to string
* @return the json string
* @throws IllegalArgumentException if invalid argument is provided
* @throws UnsupportedOperationException if the operation cannot be performed
*/
protected String encodeInternal(String key, Object event) {
logger.debug("{}: encode for {}: {}", this, key, event); // NOSONAR
/*
* It seems that sonar declares the previous logging line as a security vulnerability
* when logging the topic variable. The static code analysis indicates that
* the path starts in org.onap.policy.drools.server.restful.RestManager::decode(),
* but the request is rejected if the topic contains invalid characters (the sonar description
* mentions "/r/n/t" characters) all of which are validated against in the checkValidNameInput(topic).
* Furthermore production instances are assumed not to have debug enabled, nor the REST telemetry API
* should be published externally. An additional note is that Path URLs containing spaces and newlines
* will be rejected earlier in the HTTP protocol libraries (jetty) so an URL of the form
* "https://../to\npic" won't even make it here.
*/
ProtocolCoderToolset coderTools = coders.get(key);
try {
String json = coderTools.encode(event);
if (json != null && !json.isEmpty()) {
return json;
}
} catch (Exception e) {
logger.warn("{}: cannot encode (first) for {}: {}", this, key, event, e);
}
throw new UnsupportedOperationException("Cannot decode with gson");
}
/**
* Drools creators.
*
* @param topic topic
* @param encodedClass encoded class
* @return list of controllers
* @throws IllegalStateException illegal state
* @throws IllegalArgumentException argument
*/
protected List<DroolsController> droolsCreators(String topic, Object encodedClass) {
List<DroolsController> droolsControllers = new ArrayList<>();
String reverseKey = this.reverseCodersKey(topic, encodedClass.getClass().getName());
if (!this.reverseCoders.containsKey(reverseKey)) {
logger.warn("{}: no reverse mapping for {}", this, reverseKey);
return droolsControllers;
}
List<ProtocolCoderToolset> toolsets =
this.reverseCoders.get(reverseKey);
// There must be multiple toolsets associated with <topic,classname> reverseKey
// case 2 different controllers use the same models and register the same encoder for
// the same topic. This is assumed not to occur often but for the purpose of encoding
// but there should be no side-effects. Ownership is crosscheck against classname and
// classloader reference.
if (toolsets == null || toolsets.isEmpty()) {
throw new IllegalStateException(
"No Encoders toolsets available for topic "
+ topic
+ " encoder "
+ encodedClass.getClass().getName());
}
for (ProtocolCoderToolset encoderSet : toolsets) {
addToolsetControllers(droolsControllers, encodedClass, encoderSet);
}
if (droolsControllers.isEmpty()) {
throw new IllegalStateException(
"No Encoders toolsets available for "
+ topic
+ ":"
+ encodedClass.getClass().getName());
}
return droolsControllers;
}
private void addToolsetControllers(List<DroolsController> droolsControllers, Object encodedClass,
ProtocolCoderToolset encoderSet) {
// figure out the right toolset
String groupId = encoderSet.getGroupId();
String artifactId = encoderSet.getArtifactId();
List<CoderFilters> coderFilters = encoderSet.getCoders();
for (CoderFilters coder : coderFilters) {
if (coder.getFactClass().equals(encodedClass.getClass().getName())) {
var droolsController =
DroolsControllerConstants.getFactory().get(groupId, artifactId, "");
if (droolsController.ownsCoder(
encodedClass.getClass(), coder.getModelClassLoaderHash())) {
droolsControllers.add(droolsController);
}
}
}
}
/**
* get all filters by maven coordinates and topic.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @return list of coders
* @throws IllegalArgumentException if invalid input
*/
public List<CoderFilters> getFilters(String groupId, String artifactId, String topic) {
if (!isCodingSupported(groupId, artifactId, topic)) {
throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic));
}
String key = this.codersKey(groupId, artifactId, topic);
ProtocolCoderToolset coderTools = coders.get(key);
return coderTools.getCoders();
}
/**
* get all coders by maven coordinates and topic.
*
* @param groupId group id
* @param artifactId artifact id
* @return list of coders
* @throws IllegalArgumentException if invalid input
*/
public List<CoderFilters> getFilters(String groupId, String artifactId) {
if (groupId == null || groupId.isEmpty()) {
throw new IllegalArgumentException(INVALID_GROUP_ID_MSG);
}
if (artifactId == null || artifactId.isEmpty()) {
throw new IllegalArgumentException(INVALID_ARTIFACT_ID_MSG);
}
String key = this.codersKey(groupId, artifactId, "");
List<CoderFilters> codersFilters = new ArrayList<>();
for (Map.Entry<String, ProtocolCoderToolset> entry :
coders.entrySet()) {
if (entry.getKey().startsWith(key)) {
codersFilters.addAll(entry.getValue().getCoders());
}
}
return codersFilters;
}
/**
* get all filters by maven coordinates, topic, and classname.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @param classname classname
* @return list of coders
* @throws IllegalArgumentException if invalid input
*/
public CoderFilters getFilters(
String groupId, String artifactId, String topic, String classname) {
if (!isCodingSupported(groupId, artifactId, topic)) {
throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic));
}
if (classname == null || classname.isEmpty()) {
throw new IllegalArgumentException("classname must be provided");
}
String key = this.codersKey(groupId, artifactId, topic);
ProtocolCoderToolset coderTools = coders.get(key);
return coderTools.getCoder(classname);
}
/**
* get all coders by maven coordinates and topic.
*
* @param groupId group id
* @param artifactId artifact id
* @param topic topic
* @return list of coders
* @throws IllegalArgumentException if invalid input
*/
public ProtocolCoderToolset getCoders(
String groupId, String artifactId, String topic) {
if (!isCodingSupported(groupId, artifactId, topic)) {
throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic));
}
String key = this.codersKey(groupId, artifactId, topic);
return coders.get(key);
}
/**
* get all coders by maven coordinates and topic.
*
* @param groupId group id
* @param artifactId artifact id
* @return list of coders
* @throws IllegalArgumentException if invalid input
*/
public List<ProtocolCoderToolset> getCoders(
String groupId, String artifactId) {
if (groupId == null || groupId.isEmpty()) {
throw new IllegalArgumentException(INVALID_GROUP_ID_MSG);
}
if (artifactId == null || artifactId.isEmpty()) {
throw new IllegalArgumentException(INVALID_ARTIFACT_ID_MSG);
}
String key = this.codersKey(groupId, artifactId, "");
List<ProtocolCoderToolset> coderToolset = new ArrayList<>();
for (Map.Entry<String, ProtocolCoderToolset> entry :
coders.entrySet()) {
if (entry.getKey().startsWith(key)) {
coderToolset.add(entry.getValue());
}
}
return coderToolset;
}
/**
* get coded based on class and topic.
*
* @param topic topic
* @param codedClass class
* @return list of reverse filters
*/
public List<CoderFilters> getReverseFilters(String topic, String codedClass) {
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(UNSUPPORTED_MSG);
}
if (codedClass == null) {
throw new IllegalArgumentException(MISSING_CLASS);
}
String key = this.reverseCodersKey(topic, codedClass);
List<ProtocolCoderToolset> toolsets = this.reverseCoders.get(key);
if (toolsets == null) {
throw new IllegalArgumentException("No Coder found for " + key);
}
List<CoderFilters> coderFilters = new ArrayList<>();
for (ProtocolCoderToolset toolset : toolsets) {
coderFilters.addAll(toolset.getCoders());
}
return coderFilters;
}
/**
* returns group and artifact id of the creator of the encoder.
*
* @param topic topic
* @param fact fact
* @return the drools controller
*/
DroolsController getDroolsController(String topic, Object fact) {
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(UNSUPPORTED_MSG);
}
if (fact == null) {
throw new IllegalArgumentException(MISSING_CLASS);
}
List<DroolsController> droolsControllers = droolsCreators(topic, fact);
if (droolsControllers.isEmpty()) {
throw new IllegalArgumentException("Invalid Topic: " + topic);
}
if (droolsControllers.size() > 1) {
logger.warn(
"{}: multiple drools-controller {} for {}:{} ",
this,
droolsControllers,
topic,
fact.getClass().getName());
// continue
}
return droolsControllers.get(0);
}
/**
* returns group and artifact id of the creator of the encoder.
*
* @param topic topic
* @param fact fact
* @return list of drools controllers
*/
List<DroolsController> getDroolsControllers(String topic, Object fact) {
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(UNSUPPORTED_MSG);
}
if (fact == null) {
throw new IllegalArgumentException(MISSING_CLASS);
}
List<DroolsController> droolsControllers = droolsCreators(topic, fact);
if (droolsControllers.size() > 1) {
// unexpected
logger.warn(
"{}: multiple drools-controller {} for {}:{} ",
this,
droolsControllers,
topic,
fact.getClass().getName());
// continue
}
return droolsControllers;
}
}
|