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