0028691: Storage of Ocaf documents in XML file format in old document version
[occt.git] / src / XmlLDrivers / XmlLDrivers_DocumentRetrievalDriver.cxx
CommitLineData
b311480e 1// Created on: 2001-07-09
2// Created by: Julia DOROVSKIKH
973c2be1 3// Copyright (c) 2001-2014 OPEN CASCADE SAS
b311480e 4//
973c2be1 5// This file is part of Open CASCADE Technology software library.
b311480e 6//
d5f74e42 7// This library is free software; you can redistribute it and/or modify it under
8// the terms of the GNU Lesser General Public License version 2.1 as published
973c2be1 9// by the Free Software Foundation, with special exception defined in the file
10// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11// distribution for complete text of the license and disclaimer of any warranty.
b311480e 12//
973c2be1 13// Alternatively, this file may be used under the terms of Open CASCADE
14// commercial license or contractual agreement.
7fd59977 15
7fd59977 16
42cf5bc1 17#include <CDM_Application.hxx>
18#include <CDM_Document.hxx>
19#include <CDM_MessageDriver.hxx>
20#include <CDM_MetaData.hxx>
7fd59977 21#include <LDOM_DocumentType.hxx>
42cf5bc1 22#include <LDOM_LDOMImplementation.hxx>
7fd59977 23#include <LDOMParser.hxx>
42cf5bc1 24#include <OSD_Path.hxx>
4ff92abe 25#include <OSD_OpenFile.hxx>
42cf5bc1 26#include <PCDM_Document.hxx>
4ff92abe 27#include <PCDM_DOMHeaderParser.hxx>
42cf5bc1 28#include <Standard_Type.hxx>
29#include <TCollection_AsciiString.hxx>
30#include <TCollection_ExtendedString.hxx>
7fd59977 31#include <TDF_Data.hxx>
7fd59977 32#include <TDocStd_Document.hxx>
42cf5bc1 33#include <TDocStd_Owner.hxx>
7fd59977 34#include <UTL.hxx>
42cf5bc1 35#include <XmlLDrivers.hxx>
36#include <XmlLDrivers_DocumentRetrievalDriver.hxx>
37#include <XmlMDataStd.hxx>
38#include <XmlMDF.hxx>
39#include <XmlMDF_ADriver.hxx>
40#include <XmlMDF_ADriverTable.hxx>
41#include <XmlObjMgt.hxx>
42#include <XmlObjMgt_Document.hxx>
43#include <XmlObjMgt_RRelocationTable.hxx>
7fd59977 44
92efcf78 45IMPLEMENT_STANDARD_RTTIEXT(XmlLDrivers_DocumentRetrievalDriver,PCDM_RetrievalDriver)
46
57c28b61 47#ifdef _MSC_VER
7fd59977 48# include <tchar.h>
57c28b61 49#endif // _MSC_VER
7fd59977 50
51#include <locale.h>
52#include <Standard_Failure.hxx>
53#include <Standard_ErrorHandler.hxx>
54
55#define START_REF "START_REF"
56#define END_REF "END_REF"
4ff92abe 57
58#define MODIFICATION_COUNTER "MODIFICATION_COUNTER: "
59#define REFERENCE_COUNTER "REFERENCE_COUNTER: "
7fd59977 60
7fd59977 61//#define TAKE_TIMES
62static void take_time (const Standard_Integer, const char *,
63 const Handle(CDM_MessageDriver)&)
64#ifdef TAKE_TIMES
65;
66#else
67{}
68#endif
69
70static Standard_Integer RemoveExtraSeparator(TCollection_AsciiString& aString) {
71
72 Standard_Integer i, j, len ;
73
74 len = aString.Length() ;
57c28b61 75#ifdef _WIN32
7fd59977 76 // Case of network path, such as \\MACHINE\dir
77 for (i = j = 2 ; j <= len ; i++,j++) {
78#else
79 for (i = j = 1 ; j <= len ; i++,j++) {
80#endif
81 Standard_Character c = aString.Value(j) ;
82 aString.SetValue(i,c) ;
83 if (c == '/')
84 while(j < len && aString.Value(j+1) == '/') j++ ;
85 }
86 len = i-1 ;
87 if (aString.Value(len) == '/') len-- ;
88 aString.Trunc(len) ;
89 return len ;
90}
91static TCollection_AsciiString GetDirFromFile(const TCollection_ExtendedString& aFileName) {
92 TCollection_AsciiString theCFile=UTL::CString(aFileName);
93 TCollection_AsciiString theDirectory;
94 Standard_Integer i=theCFile.SearchFromEnd("/");
57c28b61 95#ifdef _WIN32
7fd59977 96// if(i==-1) i=theCFile.SearchFromEnd("\\");
97 if(theCFile.SearchFromEnd("\\") > i)
98 i=theCFile.SearchFromEnd("\\");
99#endif
100 if(i!=-1) theDirectory=theCFile.SubString(1,i);
101 return theDirectory;
102}
103
104static TCollection_AsciiString AbsolutePath(
105 const TCollection_AsciiString& aDirPath,
106 const TCollection_AsciiString& aRelFilePath)
107{
108 TCollection_AsciiString EmptyString = "" ;
57c28b61 109#ifdef _WIN32
7fd59977 110 if (aRelFilePath.Search(":") == 2 ||
111 (aRelFilePath.Search("\\") == 1 && aRelFilePath.Value(2) == '\\'))
112#else
113 if(aRelFilePath.Search("/") == 1)
114#endif
115 return aRelFilePath ;
116
117 TCollection_AsciiString DirPath = aDirPath, RelFilePath = aRelFilePath ;
118 Standard_Integer i,len ;
119
57c28b61 120#ifdef _WIN32
7fd59977 121 if(DirPath.Search(":") != 2 &&
122 (DirPath.Search("\\") != 1 || DirPath.Value(2) != '\\'))
123#else
124 if (DirPath.Search("/") != 1 )
125#endif
126 return EmptyString ;
127
57c28b61 128#ifdef _WIN32
7fd59977 129 DirPath.ChangeAll('\\','/') ;
130 RelFilePath.ChangeAll('\\','/') ;
131#endif
132
133 RemoveExtraSeparator(DirPath) ;
134 len = RemoveExtraSeparator(RelFilePath) ;
135
136 while (RelFilePath.Search("../") == 1) {
137 if (len == 3)
4fbddc7c 138 return EmptyString ;
7fd59977 139 RelFilePath = RelFilePath.SubString(4,len) ;
140 len -= 3 ;
141 if (DirPath.IsEmpty())
4fbddc7c 142 return EmptyString ;
7fd59977 143 i = DirPath.SearchFromEnd("/") ;
144 if (i < 0)
145 return EmptyString ;
146 DirPath.Trunc(i-1) ;
147 }
148 TCollection_AsciiString retx;
149 retx= DirPath;
150 retx+= "/";
151 retx+=RelFilePath ;
152 return retx;
153}
154
155//=======================================================================
156//function : XmlLDrivers_DocumentRetrievalDriver
157//purpose : Constructor
158//=======================================================================
159XmlLDrivers_DocumentRetrievalDriver::XmlLDrivers_DocumentRetrievalDriver()
160{
161 myReaderStatus = PCDM_RS_OK;
162}
163
164//=======================================================================
165//function : CreateDocument
166//purpose : pure virtual method definition
167//=======================================================================
168Handle(CDM_Document) XmlLDrivers_DocumentRetrievalDriver::CreateDocument()
169{
170 return new TDocStd_Document(PCDM_RetrievalDriver::GetFormat());
171}
172
173//=======================================================================
7fd59977 174//function : Read
175//purpose :
176//=======================================================================
177void XmlLDrivers_DocumentRetrievalDriver::Read
178 (const TCollection_ExtendedString& theFileName,
179 const Handle(CDM_Document)& theNewDocument,
180 const Handle(CDM_Application)& theApplication)
181{
182 myReaderStatus = PCDM_RS_DriverFailure;
183 myFileName = theFileName;
4ff92abe 184
185 std::ifstream aFileStream;
186 OSD_OpenStream (aFileStream, myFileName, std::ios::in);
187
188 if (aFileStream.is_open() && aFileStream.good())
189 {
190 Read (aFileStream, NULL, theNewDocument, theApplication);
191 }
192 else
193 {
194 myReaderStatus = PCDM_RS_OpenError;
195
196 TCollection_ExtendedString aMsg = TCollection_ExtendedString("Error: the file ") +
197 theFileName + " cannot be opened for reading";
198
199 theApplication->MessageDriver()->Write (aMsg.ToExtString());
9775fa61 200 throw Standard_Failure("File cannot be opened for reading");
4ff92abe 201 }
202}
203
204//=======================================================================
205//function : Read
206//purpose :
207//=======================================================================
208void XmlLDrivers_DocumentRetrievalDriver::Read (Standard_IStream& theIStream,
209 const Handle(Storage_Data)& /*theStorageData*/,
210 const Handle(CDM_Document)& theNewDocument,
211 const Handle(CDM_Application)& theApplication)
212{
7fd59977 213 Handle(CDM_MessageDriver) aMessageDriver = theApplication -> MessageDriver();
214 ::take_time (~0, " +++++ Start RETRIEVE procedures ++++++", aMessageDriver);
215
216 // 1. Read DOM_Document from file
217 LDOMParser aParser;
4ff92abe 218
5fce1605 219 // if myFileName is not empty, "document" tag is required to be read
220 // from the received document
221 Standard_Boolean aWithoutRoot = myFileName.IsEmpty();
222
223 if (aParser.parse(theIStream, Standard_False, aWithoutRoot))
7fd59977 224 {
225 TCollection_AsciiString aData;
226 cout << aParser.GetError(aData) << ": " << aData << endl;
227 myReaderStatus = PCDM_RS_FormatFailure;
228 return;
229 }
230 const XmlObjMgt_Element anElement= aParser.getDocument().getDocumentElement();
231 ::take_time (0, " +++++ Fin parsing XML : ", aMessageDriver);
232
233 ReadFromDomDocument (anElement, theNewDocument, theApplication);
7fd59977 234}
235
236//=======================================================================
237//function : ReadFromDomDocument
238//purpose : management of the macro-structure of XML document data
239//remark : If the application needs to use myRelocTable to retrieve additional
240// data from LDOM, this method should be reimplemented
241//=======================================================================
242
243void XmlLDrivers_DocumentRetrievalDriver::ReadFromDomDocument
244 (const XmlObjMgt_Element& theElement,
245 const Handle(CDM_Document)& theNewDocument,
246 const Handle(CDM_Application)& theApplication)
247{
248 const Handle(CDM_MessageDriver) aMsgDriver =
249 theApplication -> MessageDriver();
250 // 1. Read info // to be done
251 TCollection_AsciiString anAbsoluteDirectory = GetDirFromFile(myFileName);
252 Standard_Integer aCurDocVersion = 0;
253 TCollection_ExtendedString anInfo;
254 const XmlObjMgt_Element anInfoElem =
255 theElement.GetChildByTagName ("info");
256 if (anInfoElem != NULL) {
257 XmlObjMgt_DOMString aDocVerStr = anInfoElem.getAttribute("DocVersion");
258 if(aDocVerStr == NULL)
259 aCurDocVersion = 2;
260 else if (!aDocVerStr.GetInteger(aCurDocVersion)) {
261 TCollection_ExtendedString aMsg =
4fbddc7c 262 TCollection_ExtendedString ("Cannot retrieve the current Document version"
7fd59977 263 " attribute as \"") + aDocVerStr + "\"";
264 if(!aMsgDriver.IsNull())
4fbddc7c
O
265 aMsgDriver->Write(aMsg.ToExtString());
266 }
267
268 // oan: OCC22305 - check a document verison and if it's greater than
269 // current version of storage driver set an error status and return
c2f5b821 270 if( aCurDocVersion > XmlLDrivers::StorageVersion() )
4fbddc7c
O
271 {
272 TCollection_ExtendedString aMsg =
273 TCollection_ExtendedString ("error: wrong file version: ") +
274 aDocVerStr + " while current is " +
275 XmlLDrivers::StorageVersion();
276 myReaderStatus = PCDM_RS_NoVersion;
277 if(!aMsgDriver.IsNull())
278 aMsgDriver->Write(aMsg.ToExtString());
279 return;
7fd59977 280 }
4fbddc7c
O
281
282 if( aCurDocVersion < 2) aCurDocVersion = 2;
7fd59977 283
284 PropagateDocumentVersion(aCurDocVersion);
285
286 Standard_Boolean isRef = Standard_False;
287 for (LDOM_Node aNode = anInfoElem.getFirstChild();
288 aNode != NULL; aNode = aNode.getNextSibling()) {
289 if (aNode.getNodeType() == LDOM_Node::ELEMENT_NODE) {
290 if (XmlObjMgt::GetExtendedString ((LDOM_Element&)aNode, anInfo)) {
291
4fbddc7c
O
292 // Read ref counter
293 if(anInfo.Search(REFERENCE_COUNTER) != -1) {
294 try {
295 OCC_CATCH_SIGNALS
296 TCollection_AsciiString anInf(anInfo,'?');
4ff92abe 297 Standard_Integer aRefCounter = anInf.Token(" ",2).IntegerValue();
298 theNewDocument->SetReferenceCounter(aRefCounter);
4fbddc7c
O
299 }
300 catch (Standard_Failure) {
301 // cout << "warning: could not read the reference counter in " << aFileName << endl;
302 TCollection_ExtendedString aMsg("Warning: ");
303 aMsg = aMsg.Cat("could not read the reference counter").Cat("\0");
304 if(!aMsgDriver.IsNull())
305 aMsgDriver->Write(aMsg.ToExtString());
306 }
307 }
4ff92abe 308 else if (anInfo.Search(MODIFICATION_COUNTER) != -1) {
309 try {
310 OCC_CATCH_SIGNALS
311
312 TCollection_AsciiString anInf(anInfo,'?');
313 Standard_Integer aModCounter = anInf.Token(" ",2).IntegerValue();
314 theNewDocument->SetModifications (aModCounter);
315 }
316 catch (Standard_Failure) {
317 TCollection_ExtendedString aMsg("Warning: could not read the modification counter\0");
318 if(!aMsgDriver.IsNull())
319 aMsgDriver->Write(aMsg.ToExtString());
320 }
321 }
4fbddc7c
O
322
323 if(anInfo == END_REF)
324 isRef = Standard_False;
325 if(isRef) { // Process References
326
327 Standard_Integer pos=anInfo.Search(" ");
328 if(pos != -1) {
329 // Parce RefId, DocumentVersion and FileName
330 Standard_Integer aRefId;
331 TCollection_ExtendedString aFileName;
332 Standard_Integer aDocumentVersion;
333
334
335 TCollection_ExtendedString aRest=anInfo.Split(pos);
336 aRefId = UTL::IntegerValue(anInfo);
337
338 Standard_Integer pos2 = aRest.Search(" ");
339
340 aFileName = aRest.Split(pos2);
341 aDocumentVersion = UTL::IntegerValue(aRest);
342
343 TCollection_AsciiString aPath = UTL::CString(aFileName);
344 TCollection_AsciiString anAbsolutePath;
345 if(!anAbsoluteDirectory.IsEmpty()) {
346 anAbsolutePath = AbsolutePath(anAbsoluteDirectory,aPath);
347 if(!anAbsolutePath.IsEmpty()) aPath=anAbsolutePath;
348 }
349 if(!aMsgDriver.IsNull()) {
350 // cout << "reference found; ReferenceIdentifier: " << theReferenceIdentifier << "; File:" << thePath << ", version:" << theDocumentVersion;
351 TCollection_ExtendedString aMsg("Warning: ");
352 aMsg = aMsg.Cat("reference found; ReferenceIdentifier: ").Cat(aRefId).Cat("; File:").Cat(aPath).Cat(", version:").Cat(aDocumentVersion).Cat("\0");
353 aMsgDriver->Write(aMsg.ToExtString());
354 }
355 // Add new ref!
356 /////////////
357 TCollection_ExtendedString theFolder,theName;
358 //TCollection_ExtendedString theFile=myReferences(myIterator).FileName();
359 TCollection_ExtendedString f(aPath);
57c28b61 360#ifndef _WIN32
4fbddc7c
O
361
362 Standard_Integer i= f.SearchFromEnd("/");
363 TCollection_ExtendedString n = f.Split(i);
364 f.Trunc(f.Length()-1);
365 theFolder = f;
366 theName = n;
7fd59977 367#else
4fbddc7c
O
368 OSD_Path p = UTL::Path(f);
369 Standard_ExtCharacter chr;
370 TCollection_ExtendedString dir, dirRet, name;
371
372 dir = UTL::Disk(p);
373 dir += UTL::Trek(p);
374
375 for ( int i = 1; i <= dir.Length (); ++i ) {
376
377 chr = dir.Value ( i );
378
379 switch ( chr ) {
7c65581d 380
381 case '|':
382 dirRet += "/";
4fbddc7c 383 break;
7c65581d 384
385 case '^':
386
387 dirRet += "..";
4fbddc7c 388 break;
7fd59977 389
4fbddc7c
O
390 default:
391 dirRet += chr;
392
393 }
394 }
395 theFolder = dirRet;
396 theName = UTL::Name(p); theName+= UTL::Extension(p);
57c28b61 397#endif // _WIN32
4fbddc7c
O
398
399 Handle(CDM_MetaData) aMetaData = CDM_MetaData::LookUp(theFolder,theName,aPath,aPath,UTL::IsReadOnly(aFileName));
7fd59977 400////////////
4fbddc7c
O
401 theNewDocument->CreateReference(aMetaData,aRefId,
402 theApplication,aDocumentVersion,Standard_False);
7fd59977 403
4fbddc7c
O
404
405 }
7fd59977 406
4fbddc7c
O
407
408 }
409 if(anInfo == START_REF)
410 isRef = Standard_True;
7fd59977 411 }
412 }
413 }
414 }
415
416 // 2. Read comments
417 TCollection_ExtendedString aComment;
418 const XmlObjMgt_Element aCommentsElem =
419 theElement.GetChildByTagName ("comments");
420 if (aCommentsElem != NULL)
421 {
422 for (LDOM_Node aNode = aCommentsElem.getFirstChild();
423 aNode != NULL; aNode = aNode.getNextSibling())
424 {
425 if (aNode.getNodeType() == LDOM_Node::ELEMENT_NODE)
426 {
427 if (XmlObjMgt::GetExtendedString ((LDOM_Element&)aNode, aComment))
428 {
429 theNewDocument->AddComment(aComment);
430 }
431 }
432 }
433 }
434
435 // 2. Read Shapes section
436 if (myDrivers.IsNull()) myDrivers = AttributeDrivers (aMsgDriver);
437 const Handle(XmlMDF_ADriver) aNSDriver = ReadShapeSection(theElement, aMsgDriver);
438 if(!aNSDriver.IsNull())
439 ::take_time (0, " +++++ Fin reading Shapes : ", aMsgDriver);
440
441 // 5. Read document contents
442 try
443 {
444 OCC_CATCH_SIGNALS
0797d9d3 445#ifdef OCCT_DEBUG
7fd59977 446 TCollection_ExtendedString aMessage ("PasteDocument");
447 aMsgDriver -> Write (aMessage.ToExtString());
448#endif
449 if (!MakeDocument(theElement, theNewDocument))
450 myReaderStatus = PCDM_RS_MakeFailure;
451 else
452 myReaderStatus = PCDM_RS_OK;
453 }
9775fa61 454 catch (Standard_Failure const& anException)
7fd59977 455 {
9775fa61 456 TCollection_ExtendedString anErrorString (anException.GetMessageString());
7fd59977 457 aMsgDriver -> Write (anErrorString.ToExtString());
458 }
459
460 // Wipe off the shapes written to the <shapes> section
461 ShapeSetCleaning(aNSDriver);
462
463 // Clean the relocation table.
464 // If the application needs to use myRelocTable to retrieve additional
465 // data from LDOM, this method should be reimplemented avoiding this step
466 myRelocTable.Clear();
467 ::take_time (0, " +++++ Fin reading data OCAF : ", aMsgDriver);
468}
469
470//=======================================================================
471//function : MakeDocument
472//purpose :
473//=======================================================================
474Standard_Boolean XmlLDrivers_DocumentRetrievalDriver::MakeDocument
475 (const XmlObjMgt_Element& theElement,
476 const Handle(CDM_Document)& theTDoc)
477{
478 Standard_Boolean aResult = Standard_False;
479 Handle(TDocStd_Document) TDOC = Handle(TDocStd_Document)::DownCast(theTDoc);
480 myRelocTable.Clear();
481 if (!TDOC.IsNull())
482 {
483 Handle(TDF_Data) aTDF = new TDF_Data();
484 aResult = XmlMDF::FromTo (theElement, aTDF, myRelocTable, myDrivers);
485 if (aResult) {
486 TDOC->SetData (aTDF);
487 TDocStd_Owner::SetDocument (aTDF, TDOC);
488 }
489 }
490 return aResult;
491}
492
493//=======================================================================
494//function : AttributeDrivers
495//purpose :
496//=======================================================================
497Handle(XmlMDF_ADriverTable) XmlLDrivers_DocumentRetrievalDriver::AttributeDrivers
498 (const Handle(CDM_MessageDriver)& theMessageDriver)
499{
500 return XmlLDrivers::AttributeDrivers (theMessageDriver);
501}
502
503//=======================================================================
504//function : take_time
505//class : static
506//purpose : output astronomical time elapsed
507//=======================================================================
508#ifdef TAKE_TIMES
509#include <time.h>
510#include <sys/timeb.h>
511#include <sys/types.h>
512#include <stdio.h>
57c28b61 513#ifndef _WIN32
7fd59977 514extern "C" int ftime (struct timeb *tp);
515#endif
516extern struct timeb tmbuf0;
517
518static void take_time (const Standard_Integer isReset, const char * aHeader,
519 const Handle(CDM_MessageDriver)& aMessageDriver)
520{
521 struct timeb tmbuf;
522 ftime (&tmbuf);
523 TCollection_ExtendedString aMessage ((Standard_CString)aHeader);
524 if (isReset) tmbuf0 = tmbuf;
525 else {
526 char take_tm_buf [64];
91322f44 527 Sprintf (take_tm_buf, "%9.2f s ++++",
7fd59977 528 double(tmbuf.time - tmbuf0.time) +
529 double(tmbuf.millitm - tmbuf0.millitm)/1000.);
530 aMessage += take_tm_buf;
531 }
532 aMessageDriver -> Write (aMessage.ToExtString());
533}
534#endif
535
536//=======================================================================
537//function : PropagateDocumentVersion
538//purpose :
539//=======================================================================
540void XmlLDrivers_DocumentRetrievalDriver::PropagateDocumentVersion(
541 const Standard_Integer theDocVersion )
542{
7fd59977 543 XmlMDataStd::SetDocumentVersion(theDocVersion);
544}
545
546//=======================================================================
547//function : ReadShapeSection
548//purpose : definition of ReadShapeSection
549//=======================================================================
550Handle(XmlMDF_ADriver) XmlLDrivers_DocumentRetrievalDriver::ReadShapeSection(
551 const XmlObjMgt_Element& /*theElement*/,
4fbddc7c 552 const Handle(CDM_MessageDriver)& /*aMsgDriver*/)
7fd59977 553{
554 Handle(XmlMDF_ADriver) aDriver;
555 //empty; to be redefined
556 return aDriver;
557}
558
559//=======================================================================
560//function : ShapeSetCleaning
561//purpose : definition of ShapeSetCleaning
562//=======================================================================
563void XmlLDrivers_DocumentRetrievalDriver::ShapeSetCleaning(
4fbddc7c 564 const Handle(XmlMDF_ADriver)& /*theDriver*/)
7fd59977 565{}