1414import warnings
1515from collections import defaultdict
1616from typing import Any , Dict , Iterable , Optional , Sequence , Union
17- import msgpack
1817
1918import intelmq .lib .exceptions as exceptions
2019import intelmq .lib .harmonization
2120from intelmq import HARMONIZATION_CONF_FILE
2221from intelmq .lib import utils
2322
24- __all__ = ['Event' , 'Message' , 'MessageFactory' , 'Report' ]
23+ __all__ = ['Event' , 'Message' , 'MessageFactory' , 'Report' , 'Packer' , 'PackerMsgPack' , 'PackerJSON' ]
2524VALID_MESSSAGE_TYPES = ('Event' , 'Message' , 'Report' )
2625
26+ try :
27+ import msgpack
28+ except :
29+ msgpack = None
30+
2731
2832class MessageFactory (object ):
2933 """
@@ -60,7 +64,7 @@ def from_dict(message: dict, harmonization=None,
6064
6165 @staticmethod
6266 def unserialize (raw_message : bytes , harmonization : dict = None ,
63- default_type : Optional [str ] = None , use_packer : str = "msgpack " ) -> dict :
67+ default_type : Optional [str ] = None , use_packer : str = "MsgPack " ) -> dict :
6468 """
6569 Takes JSON-encoded Message object, returns instance of correct class.
6670
@@ -78,14 +82,13 @@ def unserialize(raw_message: bytes, harmonization: dict = None,
7882 default_type = default_type )
7983
8084 @staticmethod
81- def serialize (message ) -> bytes :
85+ def serialize (message , use_packer : str = 'MsgPack' ) -> bytes :
8286 """
8387 Takes instance of message-derived class and makes JSON-encoded Message.
8488
8589 The class is saved in __type attribute.
8690 """
87- raw_message = Message .serialize (message )
88- return raw_message
91+ return Message .serialize (message , use_packer = use_packer )
8992
9093
9194class Message (dict ):
@@ -309,30 +312,29 @@ def deep_copy(self):
309312 harmonization = {self .__class__ .__name__ .lower (): self .harmonization_config })
310313
311314 def __str__ (self ):
312- return self .serialize (use_packer = "json " )
315+ return self .serialize (use_packer = "JSON " )
313316
314- def serialize (self , use_packer : str = "msgpack " ):
317+ def serialize (self , use_packer : str = "MsgPack " ):
315318 delete_type = False
316319 if '__type' not in self :
317320 delete_type = True
318321 self ['__type' ] = self .__class__ .__name__
319322
320- if use_packer == "json" :
321- packed = json .dumps (self )
322- else :
323- packed = msgpack .packb (self )
323+ try :
324+ packer : Packer = getattr (intelmq .lib .message , f"Packer{ use_packer } " )()
325+ packed = packer .serialize (data = self )
326+ except Exception as exc :
327+ raise exceptions .SerializationError (exception = exc , object = self )
324328
325329 if delete_type :
326330 del self ['__type' ]
327331 return packed
328332
329333 @staticmethod
330- def unserialize (message : bytes , use_packer : str = "msgpack " ):
334+ def unserialize (message : bytes , use_packer : str = "MsgPack " ):
331335 try :
332- if use_packer == "json" :
333- return json .loads (message )
334- else :
335- return msgpack .unpackb (message , raw = False )
336+ packer : Packer = getattr (intelmq .lib .message , f"Packer{ use_packer } " )()
337+ return packer .unserialize (data = message )
336338 except Exception as exc :
337339 raise exceptions .UnserializationError (exception = exc , object = message )
338340
@@ -485,13 +487,13 @@ def to_dict(self, hierarchical: bool = False, with_type: bool = False,
485487
486488 return new_dict
487489
488- def to_json (self , hierarchical = False , with_type = False , jsondict_as_string = False ):
489- json_dict = self . to_dict ( hierarchical = hierarchical , with_type = with_type )
490- return json . dumps ( json_dict , ensure_ascii = False , sort_keys = True )
491-
492- def to_msgpack ( self , hierarchical = False , with_type = False ):
493- msgpack_dict = self . to_dict ( hierarchical = hierarchical , with_type = with_type )
494- return msgpack . packb ( msgpack_dict )
490+ def to_pack (self , use_packer = "MsgPack" , hierarchical = False , with_type = False , ** kwargs ):
491+ try :
492+ packer : Packer = getattr ( intelmq . lib . message , f"Packer { use_packer } " )( )
493+ data = self . to_dict ( hierarchical = hierarchical , with_type = with_type )
494+ return packer . serialize ( data , ** kwargs )
495+ except Exception as exc :
496+ raise exceptions . SerializationError ( exception = exc , object = self )
495497
496498 def __eq__ (self , other : dict ) -> bool :
497499 """
@@ -590,3 +592,38 @@ def copy(self):
590592 if 'time.observation' in retval and 'time.observation' not in self :
591593 del retval ['time.observation' ]
592594 return retval
595+
596+
597+ class Packer ():
598+ def __init__ (self ) -> None :
599+ pass
600+
601+ def serialize (self , data : bytes , ** kwargs ):
602+ raise NotImplementedError ()
603+
604+ def unserialize (self , data : bytes , ** kwargs ):
605+ raise NotImplementedError ()
606+
607+
608+ class PackerMsgPack (Packer ):
609+ def __init__ (self ) -> None :
610+ if msgpack is None :
611+ raise exceptions .MissingDependencyError ("msgpack" )
612+ super ().__init__ ()
613+
614+ def serialize (self , data , ** kwargs ):
615+ return msgpack .packb (data , ** kwargs )
616+
617+ def unserialize (self , data , ** kwargs ):
618+ return msgpack .unpackb (data , raw = False , ** kwargs )
619+
620+
621+ class PackerJSON (Packer ):
622+ def __init__ (self ) -> None :
623+ super ().__init__ ()
624+
625+ def serialize (self , data , ** kwargs ):
626+ return json .dumps (data , ** kwargs )
627+
628+ def unserialize (self , data , ** kwargs ):
629+ return json .loads (data , ** kwargs )
0 commit comments