source: Sophya/trunk/SophyaLib/BaseTools/ppersist.cc@ 2687

Last change on this file since 2687 was 2657, checked in by ansari, 20 years ago

1/ Correction petite erreur ds NDataBlock et recuperation de
MemoryObjectId a travers une fonction globale (static) ds AnyDataObj
2/ Ajout fonctions pour lister les classes PPersist handler ds ppersist.h .cc

Reza, 5 Avril 2005

File size: 19.0 KB
Line 
1#include "sopnamsp.h"
2#include "machdefs.h"
3#include <stdio.h>
4#include <sys/types.h>
5#include <time.h>
6#include "pexceptions.h"
7#include "ppersist.h"
8#include "anydataobj.h"
9#include <iostream>
10#include <iomanip>
11#include <typeinfo>
12
13// ------------------------- Historique ---------------------------
14// Le code de ppersist a ete separe en deux en Decembre 2003
15// a partir de la version CVS (1.26 - ppersist.cc) et
16// (1.19 - ppersist.h) .
17// la partie sur l'ecriture des donnees de base et leurs tableaux
18// a ete mis dans les fichiers ppfbinstream.h .cc
19// (Classes PPFBinaryInputStream et PPFBinaryOutputStream
20// -----------------------------------------------------------------
21
22
23#define MAXTAGLEN 255
24
25//++
26// Class PIOPersist
27// Lib Outils++
28// include ppersist.h
29//
30// Root class for persistant files. Handles the registration of
31// persistant classes
32//--
33
34//++
35// Links See
36// PPersist
37// PInPersist
38// POutPersist
39//--
40
41
42MD5_CONTEXT PIOPersist::ctx;
43PIOPersist::ClassList * PIOPersist::ppclassList = NULL; // $CHECK$ Reza 26/04/99
44map<string, uint_8> * PIOPersist::ppclassNameList = NULL;
45map<string, uint_8> * PIOPersist::dobjclassNameList = NULL;
46
47//++
48void
49PIOPersist::Initialize()
50// Initialisation globale (objets statiques) $CHECK$ Reza 26/04/99
51//--
52{
53ppclassList = new PIOPersist::ClassList;
54ppclassNameList = new map<string, uint_8>;
55dobjclassNameList = new map<string, uint_8>;
56cout << " PIOPersist::Initialize() Starting Sophya Persistence management service " << endl;
57}
58
59//++
60void
61PIOPersist::RegisterPPHandlerClass(uint_8 classId, string ppclass_name, ClassCreatorFunc f)
62//
63// Register a new persistence handler (PPersist) class.
64// The classId is usually a hash of the class< name, and
65// ppclass_name is typeid(PPersistClass).name() .
66// This method is called only through the PPersistRegistrar template
67//
68//--
69{
70 if (ppclassList->size() && (ppclassList->find(classId) != ppclassList->end()) ) {
71 cerr << "RegisterClass : Error, " << hex << classId << dec
72 << " already registered." << endl;
73 throw(DuplicateIdExc("PIOPersist::RegisterPPHandlerClass() Already registered (1)"));
74 }
75 if (ppclassNameList->size() && (ppclassNameList->find(ppclass_name) != ppclassNameList->end())) {
76 cerr << "RegisterClass : Error (2) " << ppclass_name
77 << " already registered." << endl;
78 throw(DuplicateIdExc("PIOPersist::RegisterPPHandlerClass() Already registered(2)"));
79 }
80
81 (*ppclassList)[classId] = f;
82 (*ppclassNameList)[ppclass_name] = classId;
83}
84
85//++
86void
87PIOPersist::RegisterDataObjClass(uint_8 classId, string class_name)
88// Register a new DataObj class corresponding to a PPersist classId
89// class_typename should be typeid(DataObject).name()
90//--
91{
92 if (ppclassList->find(classId) == ppclassList->end() ) {
93 cerr << "PIOPersist::RegisterDataObjClass() Error (1) "
94 << hex << classId << dec << " Not Found !" << endl;
95 throw( NotFoundExc("PIOPersist::RegisterDataObjClass() Not found classId ") );
96 }
97 if (dobjclassNameList->size() && (dobjclassNameList->find(class_name) != dobjclassNameList->end())) {
98 cerr << "PIOPersist::RegisterDataObjClass() Error (2)" << class_name
99 << " already registered." << endl;
100 throw(DuplicateIdExc("PIOPersist::RegisterDataObjClass() - Already registered"));
101 }
102
103 (*dobjclassNameList)[class_name] = classId;
104}
105
106// class_typename should be typeid(DataObject).name(), to be
107// used by POutPersist::PutDataObject() methods.
108
109//! Lists the registered PPersist handler classes and the corresponding class id.
110void
111PIOPersist::ListPPHandlers()
112{
113 cout << " PIOPersist::ListPPHandlers() - List of registered PPersist handler classes " << endl;
114 map<string, uint_8>::iterator it;
115 int k = 0;
116 for (it = (*ppclassNameList).begin(); it != (*ppclassNameList).end(); it++) {
117 cout << ++k << ": " << (*it).first << "\n" << " ClassId: Hex= "
118 << hex << (*it).second << " (Dec= " << dec << (*it).second << ")" << endl;
119 }
120}
121
122//! Lists the registered DataObj classes with the corresponding PPHandler name
123void
124PIOPersist::ListDataObjClasses()
125{
126 cout << " PIOPersist::ListDataObjClasses() : Registered DataObj class list " << endl;
127 map<string, uint_8>::iterator it;
128 int k = 0;
129 for (it = (*dobjclassNameList).begin(); it != (*dobjclassNameList).end(); it++) {
130 cout << ++k << "- " << (*it).first << " -> " << getPPClassName((*it).second) << endl;
131 }
132}
133
134PIOPersist::ClassCreatorFunc
135PIOPersist::FindCreatorFunc(uint_8 classId)
136// Returns the PPersist class creator function for the specified classId
137{
138 ClassList::iterator i = ppclassList->find(classId);
139 if (i == ppclassList->end()) throw(NotFoundExc("PIOPersist::FindCreatorFunc() Not found classId"));
140 return (*i).second;
141}
142
143string
144PIOPersist::getPPClassName(uint_8 classId)
145// Returns the PPersist class name for the specified classId
146{
147 map<string, uint_8>::iterator i;
148 for (i= ppclassNameList->begin(); i != ppclassNameList->end(); i++)
149 if ( (*i).second == classId ) return (*i).first;
150
151 throw(NotFoundExc("PIOPersist::getPPClassName() Not found classId"));
152}
153
154uint_8
155PIOPersist::getPPClassId(string const & typ_name)
156// Returns the classId for the specified PPersist class type name
157{
158 map<string, uint_8>::iterator i = ppclassNameList->find(typ_name);
159 if (i == ppclassNameList->end())
160 throw(NotFoundExc("PIOPersist::getPPClassId() Not found className"));
161 return (*i).second;
162}
163
164uint_8
165PIOPersist::getPPClassId(PPersist const & ppo)
166// Returns the classId for the specified PPersist class
167{
168 string typ_name = typeid(ppo).name() ;
169 return (getPPClassId(typ_name) );
170}
171
172
173string
174PIOPersist::getDataObjClassName(uint_8 classId)
175// Returns the PPersist class name for the specified classId
176{
177 map<string, uint_8>::iterator i;
178 for (i= dobjclassNameList->begin(); i != dobjclassNameList->end(); i++)
179 if ( (*i).second == classId ) return (*i).first;
180
181 throw(NotFoundExc("PIOPersist::getDataObjClassName() Not found classId"));
182}
183
184uint_8
185PIOPersist::getDataObjClassId(string const & typ_name)
186// Returns the classId for the specified PPersist class type name
187{
188 map<string, uint_8>::iterator i = dobjclassNameList->find(typ_name);
189 if (i == dobjclassNameList->end())
190 throw(NotFoundExc("PIOPersist::getDataObjClassId() Not found className"));
191 return (*i).second;
192}
193
194uint_8
195PIOPersist::getDataObjClassId(AnyDataObj const & o)
196// Returns the classId for the specified PPersist class
197{
198 string typ_name = typeid(o).name() ;
199 return (getDataObjClassId(typ_name) );
200}
201
202static inline void bswap8_hash(void* p)
203{
204 uint_8 tmp = *(uint_8*)p;
205 *(uint_8*)p = ((tmp >> (7*8)) & 0x000000FF) |
206 ((tmp >> (5*8)) & 0x0000FF00) |
207 ((tmp >> (3*8)) & 0x00FF0000) |
208 ((tmp >> (1*8)) & 0xFF000000) |
209 ((tmp & 0xFF000000) << (1*8)) |
210 ((tmp & 0x00FF0000) << (3*8)) |
211 ((tmp & 0x0000FF00) << (5*8)) |
212 ((tmp & 0x000000FF) << (7*8));
213}
214
215
216
217uint_8 PIOPersist::Hash(string const& typname) {
218 md5_init(&ctx);
219 md5_write(&ctx, (unsigned char*) typname.c_str(), typname.size());
220 md5_final(&ctx);
221 uint_8 hash1 = *((uint_8*) ctx.buf);
222 uint_8 hash2 = *((uint_8*) (ctx.buf+8));
223#if IS_BIG_ENDIAN
224 bswap8_hash(&hash1);
225 bswap8_hash(&hash2);
226#endif
227
228 return (hash1+hash2);
229}
230
231
232//++
233// Class PPersist
234// Lib Outils++
235// include ppersist.h
236//
237// Classe de base pour des objets persistants. Pour créer un objet
238// persistant :
239// - Hériter de PPersist.
240// - Définir un numéro d'identification de la classe, unique dans Peida
241// - Implémenter "ClassId()"
242// - Implémenter "WriteSelf" et "ReadSelf", qui doivent écrire toutes les variables
243// membres que l'on souhaite écrire, et les relire dans le même ordre.
244// Pour écrire une référence à un objet : l'objet doit être un PPersist,
245// et il suffit d'appeler "Write" sur cet objet, et "PPersistMgr::ReadObject".
246// Si plusieurs objets font référence au même, pour éviter de l'écrire plusieurs
247// fois, il faut que cet objet soit un PShPersist.
248// - Pour que le fichier soit portable, écrire et lire les variables membres en utilisant
249// les fonctions PutXX/GetXX de PInPersist/POutPersist.
250//
251// Attention: les méthodes à redéfinir sont WriteSelf et ReadSelf, mais il ne faut jamais
252// les appeler directement. Seuls Write et Read peuvent être appelées par l'utilisateur.
253//--
254
255//++
256// Links See
257// PInPersist
258// POutPersist
259// PIOPersist
260//--
261
262//++
263void
264PPersist::Write(string const& fn) const
265//
266// Ecrit l'objet dans un nouveau fichier ppersist "fn".
267//--
268{
269 POutPersist of(fn);
270 Write(of);
271}
272
273//++
274void
275PPersist::Read(string const& fn)
276//
277// Relit l'objet dans le fichier ppersist "fn". Il faut connaître a priori
278// le type de l'objet. Pour une relecture avec création automatique du bon
279// objet, utiliser PPersistMgr::ReadObject.
280//--
281{
282 PInPersist inf(fn);
283 Read(inf);
284}
285
286//++
287void
288PPersist::Write(POutPersist& s) const
289//
290// Ecrit l'objet dans le fichier PPersist.
291//--
292{
293 s.PutPPObject(this);
294}
295
296
297//++
298void
299PPersist::Read(PInPersist& s)
300//
301// Relit l'objet dans le fichier ppersist. Il faut connaître a priori
302// le type de l'objet. Pour une relecture avec création automatique du bon
303// objet, utiliser PInPersist::ReadObject.
304// Il faut qu'on soit un objet ecrit
305//--
306{
307 // We should be the exact type
308 // Check tag value
309 unsigned char ppstype,ppstag;
310 s.GetTypeTag(ppstype);
311 if ( (ppstype != PInPersist::PPS_OBJECT) && ( ppstype != PInPersist::PPS_REFERENCE ) ) {
312 }
313 if (ppstype == PInPersist::PPS_OBJECT) {
314 // Check class id
315 uint_8 classId;
316 s.GetRawU8(classId);
317 uint_8 oid,oid2;
318 s.GetRawU8(oid);
319 if (classId != PIOPersist::getPPClassId(*this) )
320 throw FileFormatExc("PPersist::Read (): not the same object type");
321 ReadSelf(s);
322 // Read the ENDOBJECT
323 s.GetRawUByte(ppstag);
324 if (ppstag != PInPersist::PPS_ENDOBJECT)
325 throw FileFormatExc("PPersist::Read() No PPS_ENDOBJECT tag");
326 s.GetRawU8(oid2);
327 if (oid2 != oid)
328 throw FileFormatExc("PPersist::Read() Inconsistent PPS-OId at PPS_ENDOBJECT ");
329 s.KeepOId(oid, *this); // Object should be kept with its PPS_OId (if oid > 0)
330 }
331 else if ( ppstype == PInPersist::PPS_REFERENCE )
332 s.ReadReference(*this);
333
334 else throw FileFormatExc("PPersist::Read() : not an object in flow");
335
336}
337
338//++
339void
340PPersist::Write(POutPersist& s, string const& tag) const
341//
342// Ecrit l'objet dans le fichier PPersist avec un tag
343//--
344{
345 s.WriteNameTag(tag);
346 s.PutPPObject(this);
347}
348
349//++
350void
351PPersist::ReadAtTag(PInPersist& s, string const& tag)
352//
353// Lit l'objet à la position du tag numéro "tagid".
354//--
355{
356 if (!s.GotoNameTag(tag))
357 throw NotFoundExc("PPersist::ReadAtTag tag not found");
358 Read(s);
359}
360
361// Renvoie l'identificateur de l'objet - par defaut=0
362
363uint_8
364PPersist::getMemOId() const
365{
366 return(0);
367}
368
369// Ces deux methodes doivent etre redefinies si getMemOId() renvoie non nul (>0)
370// ShareDataReference() et CloneSharedReference()
371void
372PPersist::ShareDataReference(PPersist & pcs)
373{
374 throw NotAvailableOperation("PPersist::ShareDataReference() - Unsupported operation !");
375}
376
377PPersist *
378PPersist::CloneSharedReference()
379{
380 throw NotAvailableOperation("PPersist::CloneSharedReference() - Unsupported operation !");
381}
382
383//++
384// virtual void PPersist::ReadSelf(PInPersist&)=0
385// Méthode virtuelle pure à redéfinir. Elle est appelée par Read
386// et PPersistMgr::ReadObject. Il faut relire les variables membres,
387// dans l'ordre où elles ont été écrites par WriteSelf.
388// virtual void PPersist::WriteSelf(POutPersist&) const=0
389// Méthode virtuelle pure à redéfinir. Elle est appelée par Write.
390// Il faut écrire les variables membres,
391// dans l'ordre où elles seront relues par ReadSelf.
392//--
393
394
395
396//++
397// Class PInPersist
398// Lib Outils++
399// include ppersist.h
400//
401// Fichier d'objets persistants, en lecture.
402//--
403
404PInPersist::PInPersist(RawInOutStream * is, bool ad, bool scan)
405 : PPFBinaryInputStream(is, ad, scan)
406{
407}
408
409PInPersist::PInPersist(string const& flnm, bool scan)
410 : PPFBinaryInputStream(flnm, scan)
411{
412}
413
414
415
416PInPersist::~PInPersist()
417{
418 ObjList::iterator i;
419 for(i=objList.begin(); i!= objList.end(); i++)
420 if ((*i).second) delete (*i).second;
421}
422
423
424
425string
426PInPersist::GetTagClassName(int itag)
427{
428 // A faire
429// if (itag<0 || itag >= (int)tags.size()) return "";
430// map<string, int_8>::iterator i = tags.begin();
431// for (int j=0; j<itag; j++) i++;
432// uint_8 cid = (*i).second;
433// return(GetClassName(cid));
434 return("");
435}
436
437PPersist*
438PInPersist::ReadObject()
439{
440 return(GetPPObject());
441}
442
443void
444PInPersist::GetObject(AnyDataObj & o)
445{
446 GetPPObject(&o);
447 return;
448}
449
450void
451PInPersist::GetObject(AnyDataObj & o, string tagname)
452{
453 GotoNameTag(tagname);
454 GetPPObject(&o);
455 return;
456}
457
458PPersist*
459PInPersist::GetPPObject(AnyDataObj * po)
460{
461 // Get tag
462 unsigned char ppstype;
463 GetTypeTag(ppstype);
464 if (ppstype != PPS_OBJECT && ppstype != PPS_REFERENCE && ppstype != PPS_NULL) {
465 throw FileFormatExc("PInPersist::ReadObject : not an object in flow");
466 }
467
468 if (ppstype == PPS_NULL) {
469 return NULL;
470 } else if (ppstype == PPS_OBJECT) {
471 // Get class id
472 uint_8 classId;
473 GetRawU8(classId);
474 uint_8 oid,oid2;
475 GetRawU8(oid);
476
477 // Get factory method
478 ClassCreatorFunc f = FindCreatorFunc(classId);
479 if (!f) {
480 throw NotFoundExc("PInPersist::ReadObject class not registered");
481 }
482
483 // Create object
484 PPersist* object = f();
485 // If a DataObject was specified , we assign it to the PPersistObject
486 if (po != NULL) object->SetDataObj(*po);
487
488 object->ReadSelf(*this);
489 unsigned char ppstag;
490 // Read the ENDOBJECT
491 GetRawUByte(ppstag);
492 if (ppstag != PPS_ENDOBJECT)
493 throw FileFormatExc("PInPersist::ReadObject No PPS_ENDOBJECT tag");
494 GetRawU8(oid2);
495 if (oid2 != oid)
496 throw FileFormatExc("PInPersist::ReadObject Inconsistent PPS-OId at PPS_ENDOBJECT ");
497
498 KeepOId(oid, *object);
499 return object;
500 }
501 else if (ppstype == PPS_REFERENCE)
502 return ReadReference();
503
504 else throw FileFormatExc("PInPersist::ReadObject invalide Tag Type !");
505}
506
507
508
509void
510PInPersist::ReadReference(PPersist & ppo)
511{
512 PPersist * pr = ReadReference();
513 ppo.ShareDataReference(*pr);
514}
515
516
517PPersist *
518PInPersist::ReadReference()
519{
520 uint_8 oid;
521 int_8 pos;
522 GetRawU8(oid);
523 GetRawI8(pos);
524 // cerr << " DBG - PInPersist::ReadReference-A " << oid << " Pos= " << pos << endl;
525 map<uint_8, PPersist *>::iterator i = objList.find(oid);
526 if (i != objList.end()) return (*i).second;
527 else { // We may have skeeped it !
528 // Let's try to read it
529 int_8 cpos;
530 cpos = s->tellg();
531 s->seekg(pos);
532 PPersist* ppo = ReadObject();
533 s->seekg(cpos);
534 delete ppo;
535 // cerr << " DBG - PInPersist::ReadReference-B ... " << endl;
536
537 map<uint_8, PPersist *>::iterator i2 = objList.find(oid);
538 if (i2 == objList.end())
539 throw FileFormatExc("PInPersist::ReadReference() Not found PPS_OId ");
540 return (*i2).second;
541 }
542}
543
544
545void
546PInPersist::KeepOId(uint_8 oid, PPersist & ppo)
547{
548 if ((oid&0x1) == 0) return; // This is not an object which can be referenced
549 // cerr << " DBG - PInPersist::KeepOId() " << oid << endl;
550 if ((objList.size() > 0) && (objList.find(oid) != objList.end()) ) {
551 // Ceci ne devrait arriver que si on lit dans le desordre (avec GotoNameTag)
552 // et pas avec une lecture sequentielle ... Reza 03/2000
553 // cerr << "PInPersist::KeepOId()/Warning - already present PPS_ObjectId ! " << oid << endl;
554 if (seqread) throw FileFormatExc("PInPersist::KeepOId() already present PPS_ObjectId ");
555 PPersist *pp = (*objList.find(oid)).second;
556 ppo.ShareDataReference(*pp);
557 }
558 else {
559 PPersist * npp = ppo.CloneSharedReference();
560 if (npp == NULL) throw PError("PInPersist::KeepOId() NULL returned by PPersist.Clone() ! ");
561 objList[oid] = npp;
562 }
563 return;
564}
565
566//++
567// Class POutPersist
568// Lib Outils++
569// include ppersist.h
570//
571// Fichier d'objets persistants, en écriture.
572//--
573
574
575//++
576// POutPersist(string const& flnm, int endianness = PPersist::PPS_NATIVE)
577//
578// Crée un nouveau fichier ppersist. Par défaut, il est petit=boutien
579// sur machines petit-boutiennes, et gros-boutien sur machines
580// gros-boutiennes. On peut explicitement spécifier PPersist::PPS_LITTLE_ENDIAN
581// ou PPersist::PPS_BIG_ENDIAN.
582//--
583POutPersist::POutPersist(RawInOutStream* os, bool ad, int endianness)
584 : PPFBinaryOutputStream(os, ad, endianness)
585{
586 pps_OId = 0;
587 wobj_level = 0;
588}
589
590POutPersist::POutPersist(string const& flnm, int endianness)
591 : PPFBinaryOutputStream(flnm, endianness)
592{
593 // PPS (POutPersist stream) Object Id initialisation
594 pps_OId = 0;
595 wobj_level = 0;
596}
597
598POutPersist::~POutPersist()
599{
600}
601
602
603void
604POutPersist::PutObject(AnyDataObj & o)
605{
606 ClassCreatorFunc f = FindCreatorFunc(getDataObjClassId(o));
607 if (!f)
608 throw NotFoundExc("PInPersist::PutObject() class not registered");
609 PPersist* ppo = f();
610 ppo->SetDataObj(o);
611 PutPPObject(ppo);
612}
613
614void
615POutPersist::PutObject(AnyDataObj & o, string tagname)
616{
617 WriteNameTag(tagname);
618 PutObject(o);
619}
620
621
622void
623POutPersist::PutPPObject(PPersist const* obj)
624{
625 if (serializeNullAndRepeat(obj)) return; // NULL object or already written in stream
626
627 // We have to write the object
628 uint_8 oid = assignObjectId(obj); // We assing a PPS Object Id
629 PutRawUByte(PPS_OBJECT); // We write the Object Tag
630 wobj_level++; // Niveau d'imbrication d'ecriture d'objets
631 PutRawU8(getPPClassId(*obj)); // Writing the PPersist ClassId
632 PutRawU8(oid); // Write the PPS Object Id
633 obj->WriteSelf(*this);
634 // Comptage d'objets ecrits
635 _nbobjs++;
636 if (wobj_level > _maxnestlevel) _maxnestlevel = wobj_level;
637 if (wobj_level == 1) _nbtlobjs++;
638 wobj_level--;
639 PutRawUByte(PPS_ENDOBJECT); // We write the End-Of-Object Tag
640 PutRawU8(oid); // and again its PPS Object Id
641}
642
643bool
644POutPersist::serializeNullAndRepeat(PPersist const* x)
645{
646 if (x == NULL) {
647 PutRawUByte(PPS_NULL);
648 return true;
649 }
650
651 int_8 pos;
652 uint_8 id = findObjectId(x, pos);
653 if (id > 0) {
654 PutRawUByte(PPS_REFERENCE);
655 PutRawU8(id); // Writing the corresponding object Id
656 PutRawI8(pos); // The original object position
657 _nbrefs++; // Compteur de nombre de reference ecrits
658 return true;
659 }
660
661 return false; // Object have to be written in stream ...
662}
663
664uint_8
665POutPersist::assignObjectId(PPersist const* x)
666{
667 pps_OId += 16; // We keep the three first bytes for future usage
668 // Bit 1 non zero -> Object can be referenced
669 uint_8 id = pps_OId;
670 uint_8 mid = x->getMemOId();
671 if (mid > 0) {
672 int_8 pos;
673 if (findObjectId(x,pos) > 0)
674 throw PError("POutPersist::assignObjectId() Error - Already serialized object ! ");
675 id += 1; // Bit 1 non zero -> Object can be referenced
676 objreftag rt;
677 rt.ppsoid = id;
678 // cout << " DBG-rt.ppspos = s->tellp(); " << endl;
679 rt.ppspos = s->tellp();
680 // cout << " DBG-rt.ppspos = s->tellp(); = " << rt.ppspos << endl;
681 objList[mid] = rt;
682 }
683 return id;
684}
685
686uint_8
687POutPersist::findObjectId(PPersist const* x, int_8 & pos)
688{
689 pos = -1;
690 uint_8 mid = x->getMemOId();
691 if (mid == 0) return(0);
692 ObjList::iterator i = objList.find(mid);
693 if (i == objList.end()) return 0;
694 pos = (*i).second.ppspos;
695 return (*i).second.ppsoid;
696}
697
698
Note: See TracBrowser for help on using the repository browser.