-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheatingJson.py
3739 lines (3027 loc) · 134 KB
/
eatingJson.py
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######
# @author: Ana Nieto,
# @email: nieto@lcc.uma.es
# @institution: University of Malaga
# @country: Spain
# @website: https://www.linkedin.com/in/ana-nieto-72b17718/
######
import json
import re
from abc import ABCMeta, abstractmethod
import datetime
from colorama import Fore, Style
import os
import pygraphviz as pgv # dot files
import networkx as nx
from networkx.readwrite import json_graph
import base64
import warnings
import pprint
import ntpath
import http_server
import numpy as np
import matplotlib
matplotlib.use("TkAgg") # this is for Mac OS
from matplotlib import pyplot as plt
import sys
####################################
# CLASS ANYTHING
####################################
class Anything(metaclass=ABCMeta):
#CONTEXT = Context.Context() # unique context
# Special Keys - Anything childs
SUP_USERS_KEY = 'User(id)'
SUP_DEVICES_KEY = 'Device(id)'
SUP_ADDRESS_KEY = 'Address(id)'
SUP_CARDS_KEY = 'Card(id)'
SUP_ROUTE_KEY = 'Route(id)'
SUP_SERVICE_KEY = 'Service(id)'
SUP_ACTIVITY_KEY = 'Activity(id)'
SUP_ACTION_KEY = 'Action(id)'
# Other Keys:
OBJECTS_TO_PROCESS = 'Objects(Anything)'
FILES_KEY = 'Files'
LABELS_KEY = 'Label'
TYPES_KEY = 'Type'
UNAME_KEY = 'UName'
PCODE_KEY = 'PostalCode'
COUNTRYCOD_KEY = 'Country(code)'
TIMEZONE_KEY = 'Timezone'
TIMESTAMP_KEY = 'Timestamp'
IP = 'IP'
# TYPES:
TYPES = [SUP_USERS_KEY, SUP_DEVICES_KEY, SUP_ADDRESS_KEY, SUP_CARDS_KEY, SUP_ROUTE_KEY, SUP_SERVICE_KEY,
SUP_ACTIVITY_KEY, SUP_ACTION_KEY]
# For backpack:
BACKPACK_DEFAULT_KEYS = [FILES_KEY, SUP_USERS_KEY, SUP_DEVICES_KEY, SUP_ADDRESS_KEY, SUP_CARDS_KEY, SUP_ROUTE_KEY,
SUP_SERVICE_KEY, SUP_ACTIVITY_KEY, SUP_ACTION_KEY, OBJECTS_TO_PROCESS]
# For equivalences:
EQUIVALENCES = {FILES_KEY: ['files'],
LABELS_KEY: ['label'],
SUP_ADDRESS_KEY: [SUP_ADDRESS_KEY, 'address'],
SUP_DEVICES_KEY: [SUP_DEVICES_KEY, 'device', 'sourceDevice', 'deviceSerialNumber',
'deviceId', 'serialNumber'],
SUP_USERS_KEY: [SUP_USERS_KEY, 'user', 'customerId', 'searchCustomerId', 'registeredCustomerId',
'registeredUserId', 'deviceOwnerCustomerId'],
SUP_CARDS_KEY: [SUP_CARDS_KEY, 'card'],
SUP_ROUTE_KEY: [SUP_ROUTE_KEY, 'route'],
SUP_SERVICE_KEY: [SUP_SERVICE_KEY, 'service'],
SUP_ACTIVITY_KEY: [SUP_ACTIVITY_KEY, 'activity'],
SUP_ACTION_KEY: [SUP_ACTION_KEY, 'action'],
TYPES_KEY: ['type', 'cardType', 'itemType'],
UNAME_KEY: ['username'],
PCODE_KEY: ['postalCode', 'postal', 'Zipcode'],
COUNTRYCOD_KEY: ['countryCode'],
TIMEZONE_KEY: ['timezone', 'timeZoneId', 'timeZoneRegion'],
TIMESTAMP_KEY: ['timestamp', 'creationTimestamp'],
IP: ['IP']}
# This is to maintain some statistics about the objects created...
STATISTICS = {"Total":0,
"User":{"number":0, "dicto":{}},
"Device":{"number":0, "dicto":{}},
"Address":{"number":0, "dicto":{}},
"Card":{"number":0, "dicto":{}},
"Route":{"number":0, "dicto":{}},
"Service":{"number":0, "dicto":{}},
"Activity":{"number":0, "dicto":{}},
"Action":{"number":0, "dicto":{}},}
# ---------------------------------
# CONSTRUCTOR
# ---------------------------------
def __init__(self, id, others=None, notlistable=[OBJECTS_TO_PROCESS], statistics=True):
if id is None:
raise ValueError('Unexpected value for "id", the identificator cannot be None')
self.id = id
self.history = ''
self.plotHistory = True
self.container = None # to be used if the node is printed in a graph
if others is None:
self.initBackpack()
else:
# combine backpack with the default backpack
self.initBackpack(others)
if notlistable is None:
self.notlistable = [self.OBJECTS_TO_PROCESS]
else:
self.notlistable = notlistable
self.addNotListable(self.OBJECTS_TO_PROCESS)
self.addHistory('Object created with values:%s\n' % self.printInLine())
if statistics:
key = self.__class__.__name__
values = Anything.STATISTICS.get(key)
number = values.get("number")
dicto = values.get("dicto")
check = dicto.get(id)
if check is None:
# new term
dicto.update({id:1})
else:
# item exists:
dicto[id] = dicto[id] + 1
#update:
Anything.STATISTICS["Total"] = Anything.STATISTICS["Total"] + 1
Anything.STATISTICS[key] = {"number":number+1, "dicto":dicto}
def initBackpack(self, seed=None):
"""
:return: the backpack by default
"""
#self.backpack = dict.fromkeys(Anything.BACKPACK_DEFAULT_KEYS, [])
self.backpack = {Anything.FILES_KEY:[], Anything.SUP_USERS_KEY:[], Anything.SUP_DEVICES_KEY:[],
Anything.SUP_ADDRESS_KEY:[], Anything.SUP_CARDS_KEY:[],
Anything.SUP_ROUTE_KEY:[], Anything.SUP_SERVICE_KEY:[], Anything.SUP_ACTIVITY_KEY:[],
Anything.SUP_ACTION_KEY:[], Anything.OBJECTS_TO_PROCESS:[]}
self.addHistory('Backpack initialised... ')
if seed is not None and len(seed)>0:
# add seeds to the backpack:
for s in seed:
self.backpack.update({s:seed.get(s)})
return True
# ---------------------------------
# DESTRUCTOR
# ---------------------------------
def __del__(self):
#print("%s's object %s died." % (self.__class__.__name__,self.id))
None
#----------------------------------
# METHODS TO GET THE CONTEXT
#----------------------------------
#def getContext(self):
"""
This method is to consult the structure Context of the Class
:return: the context - unique of the class
"""
# return Anything.CONTEXT
#----------------------------------
# ABSTRACT METHODS
#----------------------------------
@abstractmethod
def eatAddress(self, object):
pass
@abstractmethod
def eatRoute(self, object):
pass
@abstractmethod
def eatService(self, object):
pass
@abstractmethod
def eatUser(self, object):
pass
@abstractmethod
def eatDevice(self, object):
pass
@abstractmethod
def eatCard(self, object):
pass
@abstractmethod
def eatAction(self, object):
pass
@abstractmethod
def eatActivity(self, object):
pass
# ---------------------------------
# GET METHODS
# ---------------------------------
def getContainer(self):
"""
:return: A container to be used in a graph
"""
if self.container is None:
self.container = Container(self.getIdGraph())
self.container.setLabel(self.getId())
# Add this info in the object to be shown
self.putInBackpack('ContainerID(Web Graph)', self.container.getID())
return self.container
def isType(self, key):
"""
This method allows to check if a key correspond to one of the basic types (e.g. User)
:return: True if the key is one of the basic types, False in other case
"""
return key in Anything.TYPES
def getId(self):
"""
:return: identificator (id) of this object
"""
return self.id
def getNotListable(self):
"""
To check the elements in the backpack that are not listable
:return: list of keys that are not listable
"""
return self.notlistable
def isBlackKey(self, blackkey):
"""
To check if a key is a blackkey (not listable)
:param blackkey: key to be ckecked
:return: Ture if the key is a blackkey, false in other case
"""
return blackkey in self.getNotListable()
def getHistory(self):
"""
:return: the history of changes in the object
"""
return self.history
def getSearchTerms(self):
"""
:return: list with keys that can be used to search the items in the context of the object
"""
"Returns the keys that can be used in searches"
return self.EQUIVALENCES.keys()
def getIdGraph(self):
"""
:return: ID that is used by default to describe the object in a graph
"""
return "%s(id):%s" % (self.__class__.__name__, self.getId())
def getEquivalence(self, key, update=True):
"""
This method is for get the key to be used for get/include items in the backpack; a key can be represented in
multiple ways in this context, so this method operates such as translator
:param key: key that want to be used for search a term
:param update: if True (by default) updates the structure of EQUIVALENCES with 'key' if not included. If False
then returns None in case there is not a pre-defined equivalence
:return: the equivalence of the term to perform the search. Use the word returned in order to search for a
item in this object and/or update the context of this object.
"""
if key is None:
warnings.warn("getEquivalence>> Unexpected 'key' value, please use a string as key value")
return None
for k in Anything.EQUIVALENCES:
val = Anything.EQUIVALENCES.get(k)
#print("getEquivalence>>candidate:%s, key analysed:%s, values:%s" % (key, k, [x.lower() for x in val]))
if key.lower() in [x.lower() for x in val]:
#print(Fore.GREEN)
#print("return:%s" % k)
#print(Style.RESET_ALL)
return k
# Else, is a new term
if update:
Anything.EQUIVALENCES.update({key:[key]})
return key
return None
def getBackpack(self, key=None):
"""
:param key: if None (by default) returns all the values in backpack. In other case, this returns the values in
the backpack given the specific key value.
:return: List of items in the backpack. If there are not items, then this method returns an empty list [].
"""
if key is None:
values = list(self.backpack.values())
values = list(set([o for v in values for o in v])) #set is to remove duplicates
else:
values = self.backpack.get(self.getEquivalence(key))
if values is None: values = []
return values
def getObjectsForProcessing(self, idlist=None, key=None, remove=True):
"""
This method allows the access to the objects to be processed
:param key: if provided, only returns objects with a specific type (e.g. User)
:param remove: if True (by default) deletes the objects returned after this method is called
:return: a list of objects to be processed
"""
if key is not None and not Context.isType(key):
warnings.warn("getOjects>> Unexpected 'key' value, please provide one of the main Types (e.g. User)")
return []
returned = []
tbp = self.getBackpack(Anything.OBJECTS_TO_PROCESS)
if key is not None:
tbp = [x for x in tbp if x.__class__.__name__ == key]
if idlist is not None and len(idlist)>0:
tbp = [x for x in tbp if x.getId() in idlist]
returned = tbp
# Add to these objects info about his parent:
rf = self.getRelatedFiles()
for r in returned:
r.addRelatedFiles(rf)
r.eat(self)
if remove:
all = self.getBackpack(Anything.OBJECTS_TO_PROCESS)
not_returned = [x for x in all if x not in returned]
self.backpack.update({Anything.OBJECTS_TO_PROCESS:not_returned})
return returned
def getRelatedIDs(self):
"""
This method returns all the IDs for objects that are related with this object
:return: list of strings, where the strings are identifiers for the objects
"""
id = list(set(self.getBackpack(Anything.SUP_ADDRESS_KEY) + self.getBackpack(Anything.SUP_DEVICES_KEY)+ \
self.getBackpack(Anything.SUP_USERS_KEY) + self.getBackpack(Anything.SUP_ACTIVITY_KEY)+ \
self.getBackpack(Anything.SUP_ACTION_KEY) + self.getBackpack(Anything.SUP_CARDS_KEY)+ \
self.getBackpack(Anything.SUP_SERVICE_KEY) + self.getBackpack(Anything.SUP_ROUTE_KEY)))
return id
def getKeys(self):
"""
:return: a list of keywords to access to the backpack
"""
keys = self.backpack.keys()
return list(keys)
def getRelatedFiles(self):
"""
This method helps to consult the related files of this object
:return: A list of related files of the object
"""
return self.getBackpack(self.FILES_KEY)
def isKey(self, key):
"""
This method can be used to check if a key can be used to get a value from the backpack. Unlike 'getEquivalence',
this method allows the comparation without including the 'key' in the backpack structure
:param key: key to be checked
:return: True if the key is defined in the structure in some way (either dirctly or indireclty as equivalence),
false in other case
"""
return self.getEquivalence(key, update=False) is not None
def inBackpack(self, value):
"""
This method can be used to check if a value is in the backpack
:param object: object to be checked
:return: The keys where the object is included, empty list in other case
"""
keys = self.getKeys()
return [k for k in keys if value in self.getBackpack(k)]
def printInLine(self, line=True):
"""
This method formats this object for its comprehension in a string
:param line: True (default) if we want the description of the object in a single line. If False, then the
character '\n' is introduced
:return: a String with the description of the object
"""
lin = ""
if not line: lin = "\n"
str = "id: %s%s" % (self.getId(), lin)
for k in self.getKeys():
if k not in self.getNotListable():
item = self.getBackpack(k)
if len(item)>0:
str = "%s%s: " % (str, k)
for i in item:
# format item in backpack:
if isinstance(i, Anything):
str = "%s%s, " % (str, i.getId())
else:
str = "%s%s, " % (str, i)
str = str[0:len(str) - 1]
str += lin
if self.plotHistory:
str = "%s%s%s" % (str, self.getHistory(),lin)
return str
@staticmethod
def autolabel(rects, ax):
"""
Taken from: http://sparkandshine.net/en/draw-with-matplotlib-stacked-bar-charts-with-error-bar/
"""
# write the value inside each bar
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., height - 0.4,
'%d' % int(height), fontsize=9, ha='center', va='bottom')
@staticmethod
def plotGraph(means_frank, means_guido, label_frank, label_guido, x_label, y_label, title, bar_groups):
"""
Adapted from: https://pythonspot.com/matplotlib-bar-chart/ and
http://sparkandshine.net/en/draw-with-matplotlib-stacked-bar-charts-with-error-bar/
This method plots a graph, bar-chart, two columns each group
:param means_frank: set of values for the first bar
:param means_guido: set of values for the second bar
:param label_frank: label for the legend (first bar)
:param label_guido: label for the legend (sedond bar)
:param x_label: label for the x-axes in the graph
:param y_label: label for the y-axes in the graph
:param title: title for the plot
:param bar_groups: name of the groups
:return: this method prints a graph with the values given as parameters
"""
fig, ax = plt.subplots()
n_groups = len(bar_groups)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color='b',
label=label_frank)
rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color='g',
label=label_guido)
Anything.autolabel(rects1, ax)
Anything.autolabel(rects2, ax)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
plt.xticks(index + bar_width, bar_groups)
plt.legend()
plt.tight_layout()
plt.show()
@staticmethod
def printStatistics(printDicto=True, graph=True):
"""
Print statistics about the number of objects generated, the class of the object etc.
:param printDicto: if True (default) prints in the terminal the dictionary as it is
:return: dictionary with the statistics and the summary in form of string
"""
statistics = ""
if printDicto: pprint.pprint(Anything.STATISTICS)
statistics = "Number of objects generated (total):%d\n" % Anything.STATISTICS.get("Total")
keys = list(Anything.STATISTICS.keys())
keys.remove("Total")
total_inst_class = ()
unique_obj_class = ()
class_name = ()
for k in keys:
# Values:
values = Anything.STATISTICS.get(k)
dicto = values.get("dicto")
total = values.get("number")
num_objects = len(dicto.keys())
promed = total / num_objects
# Statistics for the class:
statistics = "%s* %s class, number of instances (total):%d, different objects:%d, " \
"average:%d per object\n" % (statistics, k, total, num_objects, promed)
total_inst_class = total_inst_class + (total,)
unique_obj_class = unique_obj_class + (num_objects,)
class_name = class_name + (k, )
# for each object in the class:
for ki in dicto.keys():
statistics = "%s ->%s:%d\n" % (statistics, ki, dicto.get(ki))
#print in a graph
if graph:
Anything.plotGraph(total_inst_class, unique_obj_class, '# Created (total)', '# Used (unique identifier)', 'Class', 'Number of instances',
'Number of instances by class', class_name)
return {'order': class_name, 'total':total_inst_class, 'unique':unique_obj_class, 'summary':statistics}
# ---------------------------------
# MODIFICATION METHODS
# ---------------------------------
def putInBackpack(self, key, inputValue, replace=True, eat=False):
"""
This method puts a value in the backpack
:param key: key in where the value will be added
:param inputValue: value to be added
:param replace: if True (by default) replace the value if exists
:param eat: if False (default) the value is not consumed. Only for values of type Anything. If eat==True, then
replace becomes False by default (because the object is eaten)
:return: True if the value was added to the backpack, False in other case
"""
if key is None or inputValue is None:
msg = "putInBackpack>> Unexpected input values key:%s, value:%s" % (key, inputValue)
warnings.warn(msg)
return False
if eat: replace=False
key = self.getEquivalence(key) #get the equivalence
values = self.getBackpack(key) # values for this key in the backpack
#print("key:%s, values:%s, inputvalues:%s" % (key, values, inputValue))
if inputValue not in values:
# new value to be added to the list:
values.append(inputValue)
else:
# this value already exists in the backpack:
index = values.index(inputValue)
if eat and isinstance(inputValue, Anything):
values[index].eat(inputValue)
elif replace:
values[index] = inputValue
#print('key:%s, values:%s' % (key, values))
self.backpack.update({key: values})
updated = inputValue in self.getBackpack(key)
return updated
def addNotListable(self, blackkey):
"""
Adds a key that will be not listable as parameter in the object
:param blackkey: key that not will be listed in a print
:return: True if was added, False in other case (perhaps because the blackkey already exists in the list
"""
if blackkey is None or not isinstance(blackkey, str):
warnings.warn("addNotListable>> Unexpected input values, please read the description of the method first")
return False
if blackkey not in self.getNotListable():
self.notlistable.append(blackkey)
return True
return False
def addHistory(self, log):
"""
This method adds a line to the history of this object
:param log: a string to be added to the history of this object
:return: True if the log was added to the history. False in other case
"""
if not isinstance(log, str):
warnings.warn("addHistory>> Unexpected 'log' value, logs must be strings!!")
return False
self.history = "%s%s>>%s\n" % (self.history, datetime.datetime.today().time().isoformat(), log)
return True
def addRelatedFiles(self, fileName):
"""
This method adds a new file related with this device (e.g. log in where it is mentioned)
:param fileName: name of the file to be added to the list. If a list is provided, then the list is processed to
include all the files in the structure
:return: True if the object was included, False in other case
"""
if fileName is None:
warnings.warn("addRelatedFiles>> Unexpected 'fileName' value, fileName must be a string")
elif isinstance(fileName, list):
ret = False
for file in fileName:
ret = ret or self.putInBackpack(self.FILES_KEY, file)
return ret
else:
return self.putInBackpack(self.FILES_KEY, fileName)
# ---------------------------------
# COMBINE INFORMATION
# ---------------------------------
def isRelatedWith(self, object):
"""
This method helps to decide if the object is related in some way with this object
:param object: the object to be checked
:return: True if the object is related with this object (based in our own criteria), False in other case
"""
return isinstance(object, Anything) and (
self.__eq__(object) or
self.inBackpack(object.getId()) or
object.inBackpack(self.getId()))
def isGoodEat(self, object, other=None):
"""
Decides if the object is good for eat based on a set of general criteria
:param object: the object from which the new data will be extracted
:param other: other parameters to be considered (None by default)
:return: True if the object can be eaten, False in other case
"""
return object is not None and isinstance(object, Anything) and (self.__eq__(object) or self.isReatedWith(object))
def eatSame(self, object, destroyIfsame=False):
"""
This method eat an object if is equal to this object
:param object: the object to be eaten
:param destroyIfsame: if False (default) the object received is not destroyed after the lunch. In other case,
the object is destroyed
:return: True if the object has been eaten, False in other case
"""
if object is None or not self.__eq__(object):
warnings.warn("eatSame (%s)>> Unexpected input values, please read the description of the method first,"
"or try 'eat' instead." % (self.__class__.__name__s))
return False
# combine backpacks:
keys2 = object.getKeys()
eat = False
for k in keys2:
values = self.getBackpack(k)
values2 = object.getBackpack(k)
for v in values2:
if v not in values:
values.append(v)
#newVal = list(set(values + values2)) #list(itertools.chain.from_iterable([values, values2])) #
# Update:
self.backpack.update({k:values})
# Destroy the last object
if destroyIfsame: object.__del__()
return eat
def eat(self, object, destroyIfsame=False):
"""
Eats the information from any object. If the object is the same it will be destroyed (by default)
:param object: object from which the new data will be extracted
:param destroyIfsame: if False (default) destroys the object received as parameter, True in other case
:return: True if the object has been eaten, False in other case
"""
if not isinstance(object, Anything):
warnings.warn("eat>> Unexpected input values, please read the description of the method firs")
return None
if not self.isRelatedWith(object):
return False
oc = object.__class__.__name__
oid = object.getId()
eaten = False
if isinstance(object, Address): eaten = self.eatAddress(object)
elif isinstance(object, Route): eaten = self.eatRoute(object)
elif isinstance(object, Service): eaten = self.eatService(object)
elif isinstance(object, User): eaten = self.eatUser(object)
elif isinstance(object, Device): eaten = self.eatDevice(object)
elif isinstance(object, Card): eaten = self.eatCard(object)
elif isinstance(object, Action): eaten = self.eatAction(object)
elif isinstance(object, Activity): eaten = self.eatActivity(object)
else:
warnings.warn("eat>> This method is not able to handle the type of Anything object, please update")
return False
if eaten:
# check the backpack in case oid is not my own id
if self.getId()!=oid and not self.inBackpack(oid):
# left a trace (only for objects different from my)
self.addHistory('Eaten object type %s, id:%s' % (oc, oid))
self.putInBackpack(oc, oid, eat=True)
if destroyIfsame: object.__del__()
return eaten
# ---------------------------------
# REDEFINED METHODS
# ---------------------------------
def __str__(self):
return self.printInLine(False)
# def __cmp__(self, other): --> no used in python3
def __cmp__(self, other):
if isinstance(other, Anything):
if (self.getId()==other.getId()):
return 0
elif (self.getId()<other.getId()):
return -1
else:
return 1
return None
def __lt__(self, other):
return self.__cmp__(other) < 0
def __eq__(self, other):
if isinstance(other, Anything):
return (self.getId() == other.getId())
return False
def __hash__(self):
return self.getId().__hash__()
####################################
# CLASS ADDRESS
####################################
class Address(Anything):
ADDRESS = 'Address'
CITY = 'City'
COUNTRY = 'Country'
LABEL = 'Label'
PLACE_ID = 'PlaceId'
SETTINGS = 'Settings'
STATE = 'State'
STATION = 'Station'
STREET = 'Street'
ZIPCODE = 'Zipcode'
TIMEZONE = 'Timezone'
IP = 'IP'
# ---------------------------------
# CONSTRUCTOR
# ---------------------------------
def __init__(self, id, addressLine1='', addressLine2='', addressLine3='', city='', countryCode='',
country='', label='', placeId=None, settings=None, state=None, stationName=None, street=None,
zipcode=None):
self.id = id
self.others = {self.ADDRESS:None, self.CITY:None, self.COUNTRY:None, self.LABEL:None, self.PLACE_ID:None,
self.SETTINGS:None, self.STATE:None, self.STATION:None, self.STREET:None, self.ZIPCODE:None}
super().__init__(id, self.others)
self.putInBackpack('AddressLine1', addressLine1)
self.putInBackpack('AddressLine2', addressLine2)
self.putInBackpack('AddressLine3', addressLine1)
self.putInBackpack('City', city)
self.putInBackpack(Anything.COUNTRYCOD_KEY, countryCode)
self.putInBackpack(Anything.LABELS_KEY, label)
self.putInBackpack('PlaceId', placeId)
self.putInBackpack('Settings', settings)
self.putInBackpack('State', state)
self.putInBackpack('stationName', stationName)
self.putInBackpack('Street', street)
self.putInBackpack('Zipcode', zipcode)
# ---------------------------------
# DESTRUCTOR
# ---------------------------------
# ---------------------------------
# GET METHODS
# ---------------------------------
def getIP(self):
"""
This method gets the IP if exists in this structure
:return: IP if exists
"""
ip = self.getBackpack(Address.IP)
if bool(ip):
return ip[0]
else:
return []
def getTimezone(self):
"""
This method gets the timezone if exists in this structure
:return: timezone value if exists
"""
timezone = self.getBackpack(Anything.TIMEZONE_KEY)
if bool(timezone):
return timezone[0]
else:
return []
def getZipCode(self):
"""
This method gets the postal code if exists in this structure
:return: postal code value if exists
"""
zipcode = self.getBackpack(Anything.PCODE_KEY)
if bool(zipcode):
return zipcode[0]
else:
return []
# ---------------------------------
# MODIFICATION METHODS
# ---------------------------------
def setIP(self, ip):
"""
This method adds a IP address to the object
:return: True if the IP was added, false in other case
"""
return self.putInBackpack(ip,Address.IP)
# ---------------------------------
# JSON OBJECT DECODING METHODS
# ---------------------------------
@staticmethod
def as_address(dct):
if dct is None:
return dct
a = dct
listkeys = ['addressId', 'asn'] #ignored keys
if 'addressId' in dct:
a = Address(dct.get('addressId'))
# The addressId is expected in base64
elif 'postalCode' in dct:
# for example, in devicePreferencess
a = Address("temporary_id_by_postalCode:%s" % dct.get('postalCode'))
elif 'asn' in dct:
# This is for a JSON with info about an IP
a = Address("temporary_id_by_ip:%s" % dct.get('ip'))
if isinstance(a, Address):
for k in dct:
if k not in listkeys: a.putInBackpack(k, dct.get(k))
return a
# ---------------------------------
# REDEFINED METHODS
# ---------------------------------
def __str__(self):
return "------------\nAddress:\n------------\n%s" % super().__str__()
def isRelatedWith(self, object):
"""
This method is redefined to add special conditions for objects of type Route
:param object: object to be checked
:return: True if the object is related to this object, False in other case
"""
res = super().isRelatedWith(object)
if isinstance(object, Route):
destId = object.getDestinationId()
origId = object.getOriginId()
res = res or (destId is not None and destId == self.getId()) or (origId is not None and origId == self.getId())
return res
#----------------------------------
# ABSTRACT METHODS IMPLEMENTED
#----------------------------------
def eatAddress(self, object):
"Eat object of this class"
if not isinstance(object, Address):
warnings.warn("eatAddress(Address)>> object type Address is expected")
return False
else: return self.eatSame(object)
def eatRoute(self, object):
"Only reads from Route in case it has any object idem to this"
if not isinstance(object, Route):
warnings.warn("eatRoute(Address)>> object type Route is expected")
return False
# only eats information about the route if the id is contained in the destination or origin of the route
if self.isRelatedWith(object):
# add if not is included:
self.putInBackpack(Anything.SUP_ROUTE_KEY, object.getId())
def eatService(self, object):
"Address does not read from Service"
if not isinstance(object, Service):
warnings.warn("eatService(Address)>> object type Service is expected")
return False
def eatUser(self, object):
"Address does not read from User"
if not isinstance(object, User):
warnings.warn("eatUser(Address)>> object type User is expected")
return False
def eatDevice(self, object):
"Address does not read from Device"
if not isinstance(object, Device):
warnings.warn("eatDevice(Address)>> object type Device is expected")
return False
def eatCard(self, object):
"Address does not read from Card"
if not isinstance(object, Card):
warnings.warn("eatCard(Address)>> object type Card is expected")
return False
def eatAction(self, object):
"Address does nor read from Action"
if not isinstance(object, Action):
warnings.warn("eatAction(Address)>> object type Action is expected")
return False
def eatActivity(self, object):
"Address does not read from Activity"
if not isinstance(object, Activity):
warnings.warn("eatActivity(Address)>> object type Activity is expected")
return False
####################################
# CLASS ROUTE
####################################
class Route(Anything):
DESTINATION = 'Destination'
ORIGIN = 'Origin'
PREFERRED_TRANSPORT = 'PreferredTransportMode'
TRANSPORT_NAMES = 'TransportNames'
WAYPOINTS = 'Waypoints'
# ---------------------------------
# CONSTRUCTOR
# ---------------------------------
def __init__(self, destinationId, originId, preferredTransport=None, transportNames=None, waypoints=[]):
self.id = "temporary id=source:%s,destination:%s" % (originId, destinationId)
super().__init__(self.id, None)
self.putInBackpack(self.ORIGIN, originId)
self.putInBackpack(self.DESTINATION, destinationId)
self.putInBackpack(self.PREFERRED_TRANSPORT, preferredTransport)
self.putInBackpack(self.WAYPOINTS, waypoints)
self.putInBackpack(self.TRANSPORT_NAMES, transportNames)
# ---------------------------------
# DESTRUCTOR
# ---------------------------------
# ---------------------------------
# GET METHODS
# ---------------------------------
def getDestinationId(self):
return self.getBackpack(self.DESTINATION)
def getOriginId(self):
return self.getBackpack(self.ORIGIN)
# ---------------------------------
# MODIFICATION METHODS
# ---------------------------------
# ---------------------------------
# JSON OBJECT DECODING METHODS
# ---------------------------------
@staticmethod
def as_route(dct):
if 'destination' in dct: