]> Creatis software - gdcm.git/blob - Testing/TestAllEntryVerify.cxx
Remove useless #include "gdcmDataImages.h"
[gdcm.git] / Testing / TestAllEntryVerify.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestAllEntryVerify.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/04/19 10:01:02 $
7   Version:   $Revision: 1.26 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18 #include "gdcmFile.h"
19
20 #include <map>
21 #include <list>
22 #include <fstream>
23 #include <iostream>
24 #include <sstream>
25
26 //Generated file:
27 //#include "gdcmDataImages.h"
28
29 typedef std::string EntryValueType;   // same type as ValEntry::value
30 typedef std::map< gdcm::TagKey, EntryValueType > MapEntryValues;
31 typedef MapEntryValues *MapEntryValuesPtr;
32 typedef std::string FileNameType;
33 typedef std::map< FileNameType, MapEntryValuesPtr > MapFileValuesType;
34
35 struct ParserException
36 {
37    std::string error;
38    static std::string Indent;
39
40    static std::string GetIndent() { return ParserException::Indent; }
41    ParserException( std::string ErrorMessage )
42    {
43       error = ErrorMessage;
44       Indent = "      ";
45    }
46    void Print() { std::cerr << Indent << error << std::endl; }
47 };
48
49 std::string ParserException::Indent = "      ";
50
51 class ReferenceFileParser
52 {
53 public:
54    ReferenceFileParser();
55    ~ReferenceFileParser();
56
57    bool Open( std::string &referenceFileName );
58    void Print();
59    void SetDataPath(std::string&);
60    bool Check();
61    bool Check( std::string fileName );
62
63 private:
64    bool AddKeyValuePairToMap( std::string &key, std::string &value );
65
66    std::istream &eatwhite(std::istream &is);
67    void eatwhite(std::string &toClean);
68    std::string ExtractFirstString(std::string &toSplit);
69    void CleanUpLine( std::string &line );
70
71    bool Check( MapFileValuesType::iterator &fileIt );
72    std::string ExtractValue(std::string &toSplit)  throw ( ParserException );
73    void ParseRegularLine( std::string &line )      throw ( ParserException );
74    void FirstPassReferenceFile()                   throw ( ParserException );
75    bool SecondPassReferenceFile()                  throw ( ParserException );
76    void HandleFileName( std::string &line )        throw ( ParserException );
77    void HandleKey( std::string &line )             throw ( ParserException );
78    bool HandleValue( std::string &line )           throw ( ParserException );
79    static uint16_t axtoi( char* );
80
81 private:
82    /// The directory containing the images to check:
83    std::string DataPath;
84
85    /// The product of the parser:
86    MapFileValuesType ProducedMap;
87
88    /// The ifstream attached to the file we parse:
89    std::ifstream from;
90
91    /// String prefixing every output
92    std::string Indent;
93
94    /// The current line position within the stream:
95    int lineNumber;
96
97    /// The currently parsed filename:
98    std::string CurrentFileName;
99
100    /// The currently parsed key:
101    std::string CurrentKey;
102
103    /// The currently parsed value:
104    std::string CurrentValue;
105
106    /// The current MapEntryValues pointer:
107    MapEntryValues *CurrentMapEntryValuesPtr;
108 };
109
110 ReferenceFileParser::ReferenceFileParser()
111 {
112    lineNumber = 1;
113    Indent = "      ";
114 }
115
116 ReferenceFileParser::~ReferenceFileParser()
117 {
118    for (MapFileValuesType::iterator i  = ProducedMap.begin();
119                                     i != ProducedMap.end();
120                                   ++i)
121    {
122       delete i->second;
123    }
124 }
125
126 /// As got from:
127 /// http://community.borland.com/article/0,1410,17203,0.html
128 uint16_t ReferenceFileParser::axtoi(char *hexStg) 
129 {
130    int n = 0;         // position in string
131    int m = 0;         // position in digit[] to shift
132    int count;         // loop index
133    int intValue = 0;  // integer value of hex string
134    int digit[5];      // hold values to convert
135    while (n < 4) 
136    {
137       if (hexStg[n]=='\0')
138          break;
139       if (hexStg[n] > 0x29 && hexStg[n] < 0x40 )    //if 0 to 9
140          digit[n] = hexStg[n] & 0x0f;               //convert to int
141       else if (hexStg[n] >='a' && hexStg[n] <= 'f') //if a to f
142          digit[n] = (hexStg[n] & 0x0f) + 9;         //convert to int
143       else if (hexStg[n] >='A' && hexStg[n] <= 'F') //if A to F
144          digit[n] = (hexStg[n] & 0x0f) + 9;         //convert to int
145       else break;
146      n++;
147    }
148    count = n;
149    m = n - 1;
150    n = 0;
151    while(n < count) 
152    {
153       // digit[n] is value of hex digit at position n
154       // (m << 2) is the number of positions to shift
155       // OR the bits into return value
156       intValue = intValue | (digit[n] << (m << 2));
157       m--;   // adjust the position to set
158       n++;   // next digit to process
159    }
160    return (uint16_t)intValue;
161 }
162
163 void ReferenceFileParser::SetDataPath( std::string &inDataPath )
164 {
165    DataPath = inDataPath;
166 }
167
168 bool ReferenceFileParser::AddKeyValuePairToMap( std::string &key, 
169                                                 std::string &value )
170 {
171    if ( !CurrentMapEntryValuesPtr )
172       return false;
173    if ( CurrentMapEntryValuesPtr->count(key) != 0 )
174       return false;
175    (*CurrentMapEntryValuesPtr)[key] = value;
176    
177    return true; //??
178 }
179
180 void ReferenceFileParser::Print()
181 {
182    for (MapFileValuesType::iterator i  = ProducedMap.begin();
183                                     i != ProducedMap.end();
184                                   ++i)
185    {
186       std::cout << Indent << "FileName: " << i->first << std::endl;
187       MapEntryValuesPtr KeyValues = i->second;
188       for (MapEntryValues::iterator j  = KeyValues->begin();
189                                     j != KeyValues->end();
190                                   ++j)
191       {
192          std::cout << Indent
193               << "  Key: "   << j->first
194               << "  Value: " << j->second
195               << std::endl;
196       }
197       std::cout << Indent << std::endl;
198    }
199    std::cout << Indent << std::endl;
200 }
201
202 bool ReferenceFileParser::Check()
203 {
204    bool ret = true;
205    for (MapFileValuesType::iterator i  = ProducedMap.begin();
206                                     i != ProducedMap.end();
207                                   ++i)
208    {
209       ret &= Check(i);
210    }
211    std::cout << Indent << std::endl;
212    return ret;
213 }
214
215 bool ReferenceFileParser::Check( std::string fileName )
216 {
217    MapFileValuesType::iterator it = ProducedMap.find(fileName);
218    if( it != ProducedMap.end() )
219    {
220       return Check(it);
221    }
222    std::cerr << Indent << "Failed\n"
223              << Indent << "Image not found :"
224              << fileName << std::endl;
225    return false;
226 }
227
228 bool ReferenceFileParser::Check( MapFileValuesType::iterator &fileIt )
229 {
230    std::string fileName = DataPath + fileIt->first;
231    std::cout << Indent << "FileName: " << fileName << std::endl;
232    gdcm::File *tested = new gdcm::File( fileName.c_str() );
233    if( !tested->IsReadable() )
234    {
235      std::cerr << Indent << "Failed\n"
236                << Indent << "Image not gdcm compatible:"
237                << fileName << std::endl;
238      delete tested;
239      return false;
240    }
241
242    MapEntryValuesPtr KeyValues = fileIt->second;
243    for (MapEntryValues::iterator j  = KeyValues->begin();
244                                  j != KeyValues->end();
245                                ++j)
246    {
247       std::string key = j->first;
248
249       std::string groupString  = key.substr( 0, 4 );
250       std::string groupElement = key.substr( key.find_first_of( "|" ) + 1, 4 );
251
252       uint16_t group   = axtoi( &(groupString[0]) );
253       uint16_t element = axtoi( &(groupElement[0]) );
254
255       std::string testedValue = tested->GetEntryValue(group, element);
256       if ( testedValue != j->second )
257       {
258          // Oops make sure this is only the \0 that differ
259          if( testedValue[j->second.size()] != '\0' ||
260              strncmp(testedValue.c_str(), 
261                      j->second.c_str(), j->second.size()) != 0)
262          {
263             std::cout << Indent << "Failed\n"
264                       << Indent << "Uncorrect value for key " 
265                       << key << std::endl
266                       << Indent << "   read value      [" 
267                       << testedValue << "]" << std::endl
268                       << Indent << "   reference value [" 
269                       << j->second << "]" << std::endl;
270             return false;
271          }
272       }
273    }
274    delete tested;
275    std::cout << Indent << "  OK" << std::endl;
276
277    return true;
278 }
279
280 std::istream &ReferenceFileParser::eatwhite( std::istream &is )
281 {
282    char c;
283    while (is.get(c)) {
284       if (!isspace(c)) {
285          is.putback(c);
286          break;
287       }
288    }
289    return is;
290 }
291
292 void ReferenceFileParser::eatwhite( std::string &toClean )
293 {
294    while( toClean.find_first_of( " " ) == 0  )
295       toClean.erase( 0, toClean.find_first_of( " " ) + 1 );
296 }
297
298 std::string ReferenceFileParser::ExtractFirstString( std::string &toSplit )
299 {
300    std::string firstString;
301    eatwhite( toSplit );
302    if ( toSplit.find( " " ) == std::string::npos ) {
303       firstString = toSplit;
304       toSplit.erase();
305       return firstString;
306    }
307    firstString = toSplit.substr( 0, toSplit.find(" ") );
308    toSplit.erase( 0, toSplit.find(" ") + 1);
309    eatwhite( toSplit );
310    return firstString;
311 }
312
313 std::string ReferenceFileParser::ExtractValue( std::string &toSplit )
314    throw ( ParserException )
315 {
316    eatwhite( toSplit );
317    std::string::size_type beginPos = toSplit.find_first_of( '"' );
318    std::string::size_type   endPos = toSplit.find_last_of( '"' );
319
320    // Make sure we have at most two " in toSplit:
321    //std::string noQuotes = toSplit.substr( beginPos + 1, endPos - beginPos - 1);
322    //if ( noQuotes.find_first_of( '"' ) != std::string::npos )
323    //   throw ParserException( "more than two quote character" );
324    if ( toSplit.find_first_of( '"',beginPos+1 ) != endPos )
325       throw ParserException( "more than two quote character" );
326
327    // No leading quote means this is not a value:
328    if ( beginPos == std::string::npos )
329    {
330       return std::string();
331    }
332
333    if ( ( endPos == std::string::npos ) || ( beginPos == endPos ) )
334       throw ParserException( "unmatched \" (quote character)" );
335
336    if ( beginPos != 0 )
337    {
338       std::ostringstream error;
339       error  << "leading character ["
340              << toSplit.substr(beginPos -1, 1)
341              << "] before opening \" ";
342       throw ParserException( error.str() );
343    }
344
345    // When they are some extra characters at end of value, it must
346    // be a space:
347    if (   ( endPos != toSplit.length() - 1 )
348        && ( toSplit.substr(endPos + 1, 1) != " " ) )
349    {
350       std::ostringstream error;
351       error  << "trailing character ["
352              << toSplit.substr(endPos + 1, 1)
353              << "] after value closing \" ";
354       throw ParserException( error.str() );
355    }
356
357    std::string value = toSplit.substr( beginPos + 1, endPos - beginPos - 1 );
358    toSplit.erase(  beginPos, endPos - beginPos + 1);
359    eatwhite( toSplit );
360    return value;
361 }
362
363 /// \brief   Checks the block syntax of the incoming ifstream. Checks that
364 ///          - no nested blocks are present
365 ///          - we encounter a matching succesion of "[" and "]"
366 ///          - when ifstream terminates the last block is closed.
367 ///          - a block is not opened and close on the same line
368 /// @param   from The incoming ifstream to be checked.
369 /// @return  True when incoming ifstream has a correct syntax, false otherwise.
370 /// \warning The underlying file pointer is not preseved.
371 void ReferenceFileParser::FirstPassReferenceFile() throw ( ParserException )
372 {
373    std::string line;
374    lineNumber = 1;
375    bool inBlock = false;
376    from.seekg( 0, std::ios::beg );
377
378    while ( ! from.eof() )
379    {
380       std::getline( from, line );
381
382       /// This is how we usually end the parsing because we hit EOF:
383       if ( ! from.good() )
384       {
385          if ( ! inBlock )
386             break;
387          else
388             throw ParserException( "Syntax error: EOF reached when in block.");
389       }
390
391       // Don't try to parse comments (weed out anything after first "#"):
392       if ( line.find_first_of( "#" ) != std::string::npos )
393       {
394          line.erase( line.find_first_of( "#" ) );
395       }
396
397       // Two occurences of opening blocks on a single line implies nested
398       // blocks which is illegal:
399       if ( line.find_first_of( "[" ) != line.find_last_of( "[" ) )
400       {
401          std::ostringstream error;
402          error << "Syntax error: nested block (open) in reference file"
403                << std::endl
404                << ParserException::GetIndent()
405                << "   at line " << lineNumber << std::endl;
406          throw ParserException( error.str() );
407       }
408
409       // Two occurences of closing blocks on a single line implies nested
410       // blocks which is illegal:
411       if ( line.find_first_of( "]" ) != line.find_last_of( "]" ) )
412       {
413          std::ostringstream error;
414          error << "Syntax error: nested block (close) in reference file"
415                << std::endl
416                << ParserException::GetIndent()
417                << "   at line " << lineNumber << std::endl;
418          throw ParserException( error.str() );
419       }
420
421       bool beginBlock ( line.find_first_of("[") != std::string::npos );
422       bool endBlock   ( line.find_last_of("]")  != std::string::npos );
423
424       // Opening and closing of block on same line:
425       if ( beginBlock && endBlock )
426       {
427          std::ostringstream error;
428          error << "Syntax error: opening and closing on block on same line "
429                << lineNumber++ << std::endl;
430          throw ParserException( error.str() );
431       }
432
433       // Illegal closing block when block not open:
434       if ( !inBlock && endBlock )
435       {
436          std::ostringstream error;
437          error << "Syntax error: unexpected end of block at line "
438                << lineNumber++ << std::endl;
439          throw ParserException( error.str() );
440       }
441   
442       // Uncommented line outside of block is not clean:
443       if ( !inBlock && !beginBlock )
444       {
445          continue;
446       }
447
448       if ( inBlock && beginBlock )
449       {
450          std::ostringstream error;
451          error << "   Syntax error: illegal opening of nested block at line "
452                << lineNumber++ << std::endl;
453          throw ParserException( error.str() );
454       }
455
456       // Normal situation of opening block:
457       if ( beginBlock )
458       {
459          inBlock = true;
460          lineNumber++;
461          continue;
462       }
463
464       // Normal situation of closing block:
465       if ( endBlock )
466       {
467          inBlock = false;
468          lineNumber++;
469          continue;
470       }
471       // This line had no block delimiter
472       lineNumber++;
473    }
474
475    // We need rewinding:
476    from.clear();
477    from.seekg( 0, std::ios::beg );
478 }
479
480 bool ReferenceFileParser::Open( std::string &referenceFileName )
481 {
482    from.open( referenceFileName.c_str(), std::ios::in );
483    if ( !from.is_open() )
484    {
485       std::cerr << Indent << "Can't open reference file." << std::endl;
486    }
487    
488    try
489    {
490       FirstPassReferenceFile();
491       SecondPassReferenceFile();
492    }
493    catch ( ParserException except )
494    {
495       except.Print();
496       return false;
497    }
498
499    from.close();
500    return true; //??
501 }
502
503 void ReferenceFileParser::CleanUpLine( std::string &line )
504 {
505    // Cleanup from comments:
506    if ( line.find_first_of( "#" ) != std::string::npos )
507       line.erase( line.find_first_of( "#" ) );
508
509    // Cleanup everything after end block delimiter:
510    if ( line.find_last_of( "]" ) != std::string::npos )
511       line.erase( line.find_last_of( "]" ) + 1 );
512
513    // Cleanup leading whites and skip empty lines:
514    eatwhite( line );
515 }
516
517 void ReferenceFileParser::HandleFileName( std::string &line )
518    throw ( ParserException )
519 {
520    if ( line.length() == 0 )
521       throw ParserException( "empty line on call of HandleFileName" );
522
523    if ( CurrentFileName.length() != 0 )
524       return;
525
526    CurrentFileName = ExtractFirstString(line);
527 }
528
529 void ReferenceFileParser::HandleKey( std::string &line )
530    throw ( ParserException )
531 {
532    if ( CurrentKey.length() != 0 )
533       return;
534
535    CurrentKey = ExtractFirstString(line);
536    if ( CurrentKey.find_first_of( "|" ) == std::string::npos )
537    {
538       std::ostringstream error;
539       error  << "uncorrect key:" << CurrentKey;
540       throw ParserException( error.str() );
541    }
542 }
543
544 bool ReferenceFileParser::HandleValue( std::string &line )
545    throw ( ParserException )
546 {
547    if ( line.length() == 0 )
548       throw ParserException( "empty line in HandleValue" );
549
550    if ( CurrentKey.length() == 0 )
551    {
552       std::cout << Indent << "No key present:" << CurrentKey << std::endl;
553       return false;
554    }
555    
556    std::string newCurrentValue = ExtractValue(line);
557    if ( newCurrentValue.length() == 0 )
558    {
559       std::cout << Indent << "Warning: empty value for key:"
560                      << CurrentKey << std::endl;
561    }
562
563    CurrentValue += newCurrentValue;
564    return true;
565 }
566
567 void ReferenceFileParser::ParseRegularLine( std::string &line)
568    throw ( ParserException )
569 {
570    if ( line.length() == 0 )
571       return;
572
573    // First thing is to get a filename:
574    HandleFileName( line );
575
576    if ( line.length() == 0 )
577       return;
578
579    // Second thing is to get a key:
580    HandleKey( line );
581        
582    if ( line.length() == 0 )
583       return;
584
585    // Third thing is to get a value:
586    if ( ! HandleValue( line ) )
587       return;
588
589    if ( CurrentKey.length() && CurrentValue.length() )
590    {
591       if ( ! AddKeyValuePairToMap( CurrentKey, CurrentValue ) )
592          throw ParserException( "adding to map of (key, value) failed" );
593       CurrentKey.erase();
594       CurrentValue.erase();
595    }
596 }
597
598 bool ReferenceFileParser::SecondPassReferenceFile()
599    throw ( ParserException )
600 {
601    gdcm::TagKey key;
602    EntryValueType value;
603    std::string line;
604    bool inBlock = false;
605    lineNumber = 0;
606
607    while ( !from.eof() )
608    {
609       std::getline( from, line );
610       lineNumber++;
611
612       CleanUpLine( line );
613
614       // Empty lines don't require any treatement:
615       if ( line.length() == 0 )
616          continue;
617
618       bool beginBlock ( line.find_first_of("[") != std::string::npos );
619       bool endBlock   ( line.find_last_of("]")  != std::string::npos );
620
621       // Waiting for a block to be opened. Meanwhile, drop everything:
622       if ( !inBlock && !beginBlock )
623          continue;
624
625       if ( beginBlock )
626       {
627          inBlock = true;
628          line.erase( 0, line.find_first_of( "[" ) + 1 );
629          eatwhite( line );
630          CurrentMapEntryValuesPtr = new MapEntryValues();
631       }
632       else if ( endBlock )
633       {
634          line.erase( line.find_last_of( "]" ) );
635          eatwhite( line );
636          ParseRegularLine( line );
637          ProducedMap[CurrentFileName] = CurrentMapEntryValuesPtr;
638          inBlock = false;
639          CurrentFileName.erase();
640       }
641    
642       // Outside block lines are dropped:
643       if ( ! inBlock )
644          continue;
645
646       ParseRegularLine( line );
647    }
648    return true; //??
649 }
650
651 int TestAllEntryVerify(int argc, char *argv[]) 
652 {
653    if ( argc > 2 )
654    {
655       std::cerr << "   Usage: " << argv[0]
656                 << " fileName" << std::endl;
657       return 1;
658    }
659
660    std::string referenceDir = GDCM_DATA_ROOT;
661    referenceDir       += "/";
662    std::string referenceFilename = referenceDir + "TestAllEntryVerifyReference.txt";
663    
664    std::cout << "   Description (Test::TestAllEntryVerify): "
665         << std::endl;
666    std::cout << "   For all images (not blacklisted in gdcm/Test/CMakeLists.txt)"
667         << std::endl;
668    std::cout << "   encountered in directory: " << GDCM_DATA_ROOT << std::endl;
669    std::cout << "   apply the following tests : "<< std::endl;
670    std::cout << "   step 1: parse the image and call IsReadable(). "  << std::endl;
671    std::cout << "   step 2: look for the entry corresponding to the image" << std::endl;
672    std::cout << "           in the reference file: \n" 
673              << "           " << referenceFilename << std::endl;
674    std::cout << "   step 3: check that each reference tag value listed for this"
675         << std::endl;
676    std::cout << "           entry matches the tag encountered at parsing step 1."
677         << std::endl << std::endl;
678
679    ReferenceFileParser Parser;
680    if ( !Parser.Open(referenceFilename) )
681    {
682       std::cout << "   failed"
683                 << "   Corrupted reference file name: "
684                 << referenceFilename << std::endl;
685       return 1;
686    }
687    Parser.SetDataPath(referenceDir);
688    // Parser.Print();
689    std::cout << "Reference file loaded -->\n"
690              << "Check files : \n";
691
692    int ret;
693    if ( argc >= 2 )
694    {
695       ret = Parser.Check( argv[1] );
696    }
697    else
698    {
699       ret = Parser.Check(); 
700    }
701    return !ret;
702 }