1 #include <creaImageIOTreeHandlerImageAdder.h>
2 #include <creaImageIOSystem.h>
3 #include <boost/filesystem.hpp>
4 #include <boost/algorithm/string.hpp>
5 #include <boost/utility.hpp>
8 namespace fs = boost::filesystem;
9 using boost::filesystem::path;
15 using namespace boost;
19 //====================================================================
21 TreeHandlerImageAdder::TreeHandlerImageAdder(TreeHandler* tree)
26 TreeHandlerImageAdder::~TreeHandlerImageAdder()
29 //====================================================================
31 //====================================================================
32 void TreeHandlerImageAdder::ConnectProgressObserver(ProgressCallbackType callback)
34 mProgressSignal.connect(callback);
36 //====================================================================
38 //=====================================================================
39 bool TreeHandlerImageAdder::IsHandledFile( const std::string& filename)
41 return (mReader.CanRead(filename));
43 //=====================================================================
45 //=====================================================================
46 void TreeHandlerImageAdder::AddFiles( const std::vector<std::string>& filenames)
50 unsigned int nbf = filenames.size();
51 std::vector<std::string>::const_iterator i;
52 mSynchronizer->GetList(mCurrentDB);
53 for (i=filenames.begin();i!=filenames.end();++i)
56 mProgress.IncNumberScannedFiles();
57 if (IsHandledFile(*i))
59 mProgress.IncNumberHandledFiles();
60 if(mSynchronizer->isIndexed(*i))
62 mSynchronizer->InsertAddOp((*i),"0","1",mCurrentDB);
63 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","ADD_OPS","PATH",(*i),mCurrentDB);
64 std::stringstream removedOn;
66 mSynchronizer->InsertIgnoreFile(addKey,(*i),"0",removedOn.str(),mCurrentDB);
70 mProgressSignal(mProgress);
71 if (mProgress.GetStop()) break;
74 //=====================================================================
76 //=====================================================================
77 void TreeHandlerImageAdder::AddDirectory( const std::string& directory,
81 std::stringstream files;
83 std::stringstream rec;
85 mSynchronizer->InsertAddOp(directory,rec.str(),"0",mCurrentDB);
86 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","ADD_OPS","PATH",directory,mCurrentDB);
87 mTreeHandler->BeginTransaction();
88 mSynchronizer->GetList(mCurrentDB);
89 AddDirectoryRecursor( directory, recurse, addKey );
90 //DicomImageScanner sc;
91 //AddDirectoryRecursorScanner(directory, recurse, addKey, sc, false );
93 int nFiles=GetProgress().GetNumberAddedFiles();
95 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",files.str(),"ADD_KEY",addKey,mCurrentDB);
96 mTreeHandler->EndTransaction();
97 GimmickDebugMessage(3,mProgress<<std::endl);
100 //=====================================================================
101 void TreeHandlerImageAdder::AddFile( const std::string& filename )
103 GimmickDebugMessage(4,"Adding '"<<filename<<"'"<<std::endl);
104 std::map< std::string, std::string> attr;
105 mTreeHandler->GetTree().GetDescriptor().BuildAttributeMap(attr);
108 mReader.ReadAttributes(filename,attr);
109 //// TO DO Create a function to test if the SOP Instance ID (0008,0018) is not already on DB
110 //// test befor if this attr is present on DB if not don't perform the test!!!
111 //bool bSOPIID = false;
112 //std::map<std::string, std::string>::iterator it_att = attr.begin();
113 //for(; it_att != attr.end(); it_att++)
115 // if (it_att->first == "D0008_0018")
117 // bSOPIID = mTreeHandler->TestSOPIID(it_attr->second);
124 int lev = mTreeHandler->AddBranch(attr);
126 // update the progress according to lev
127 if (lev<mTreeHandler->GetTree().GetNumberOfLevels())
128 mProgress.IncNumberAddedFiles();
130 //=====================================================================
132 void TreeHandlerImageAdder::RemoveFile( tree::Node* node)
134 int n=node->GetNumberOfChildren();
137 RemoveFiles(node->GetChildrenList());
145 //=====================================================================
147 void TreeHandlerImageAdder::RemoveFiles(const std::vector<tree::Node*>& nodes)
149 std::vector<tree::Node*>::const_iterator it;
150 for(it=nodes.begin();it!=nodes.end();++it)
152 int n=(*it)->GetNumberOfChildren();
155 RemoveFiles((*it)->GetChildrenList());
166 void TreeHandlerImageAdder::remove( tree::Node* i_node)
168 std::string path=i_node->GetAttribute("FullFileName");
170 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","IGNORED_FILES","PATH",path,mCurrentDB);
171 //Gets the number of files added
172 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",addKey,mCurrentDB)).c_str());
174 std::stringstream out;
176 //Sets the new number of files
177 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",out.str(),"ADD_KEY",addKey,mCurrentDB);
178 //Sets the file as removed
179 mSynchronizer->SetAttribute("REMOVE","IGNORED_FILES","1","PATH = '"+path+"' AND ADD_KEY",addKey,mCurrentDB);
183 //=======================================================================
184 //=====================================================================
185 #if defined(USE_GDCM2)
187 void TreeHandlerImageAdder::AddDirectoryRecursorScanner(const std::string &dirpath,
188 bool recursive,const std::string &addKey, DicomImageScanner i_sc, bool b_loaded)
190 GimmickDebugMessage(4,"Scanning '"<<dirpath<<"'"<<std::endl);
191 mProgress.IncNumberScannedDirs();
193 if ( !fs::exists( dirpath ) ) return;
194 time_t lastModif=fs::last_write_time(dirpath);
198 std::map< std::string, std::string> attr;
199 mTreeHandler->GetTree().GetDescriptor().BuildAttributeMap(attr);
200 std::string path = dirpath.c_str();
201 i_sc.addDirectory(path, attr);
204 fs::directory_iterator end_itr; // default construction yields past-the-end
205 for ( fs::directory_iterator itr( dirpath );
210 // If is directory & recurse : do recurse
211 if ( fs::is_directory(itr->status()) )
215 AddDirectoryRecursorScanner( itr->string(), recursive, addKey, i_sc, true);
220 std::string parent_id;
221 // tTest if directory (and only it) exists or not.
222 bool valid = mSynchronizer->isIndexed(itr->string());//true;//=mTimestampHandler->AddDirectory(dirpath, itr->string(), lastModif, time(0),mCurrentDB);
225 std::string path(itr->string());
226 mProgress.IncNumberScannedFiles();
227 boost::algorithm::replace_all( path,INVALID_FILE_SEPARATOR,VALID_FILE_SEPARATOR);
228 i_sc.ReadAttributes(itr->string(),attr);
229 // mTreeHandler->GetTopLevelNodeId("FullFileName",itr->string(),parent_id);
230 mTreeHandler->AddBranch(attr);
231 mProgress.IncNumberHandledFiles();
232 std::stringstream removedOn;
234 mSynchronizer->InsertIgnoreFile(addKey, path,"0",removedOn.str(),mCurrentDB);
237 mProgressSignal(mProgress);
238 if (mProgress.GetStop())
249 //=====================================================================
250 void TreeHandlerImageAdder::AddDirectoryRecursor(const std::string &dirpath,
252 const std::string &addKey)
254 GimmickDebugMessage(4,"Scanning '"<<dirpath<<"'"<<std::endl);
255 mProgress.IncNumberScannedDirs();
257 if ( !fs::exists( dirpath ) ) return;
258 time_t lastModif=fs::last_write_time(dirpath);
261 fs::directory_iterator end_itr; // default construction yields past-the-end
262 for ( fs::directory_iterator itr( dirpath );
266 // If is directory & recurse : do recurse
267 if ( fs::is_directory(itr->status()) )
271 AddDirectoryRecursor( itr->string(), recursive, addKey);
276 std::string parent_id;
277 // tTest if directory (and only it) exists or not.
278 bool valid = mSynchronizer->isIndexed(itr->string());//true;//=mTimestampHandler->AddDirectory(dirpath, itr->string(), lastModif, time(0),mCurrentDB);
281 mProgress.IncNumberScannedFiles();
282 if (IsHandledFile(itr->string()))
284 mProgress.IncNumberHandledFiles();
285 AddFile( itr->string() );
286 //mTreeHandler->GetTopLevelNodeId("FullFileName",itr->string(),parent_id);
287 std::stringstream removedOn;
289 mSynchronizer->InsertIgnoreFile(addKey, itr->string(),"0",removedOn.str(),mCurrentDB);
292 mProgressSignal(mProgress);
293 if (mProgress.GetStop())
304 //=======================================================================
307 //=======================================================================
309 void TreeHandlerImageAdder::CheckSyncDirectory(const std::string &dirpath,
312 bool checkAttributes,
313 std::vector<std::string> &i_ignorefiles,
314 std::vector<std::string> & attsModified,
315 std::vector<std::string> & newfiles)
317 if ( !fs::exists( dirpath ) ) return;
318 fs::directory_iterator end_itr; // default construction yields past-the-end
320 for ( fs::directory_iterator itr( dirpath ); itr != end_itr; ++itr )
322 // If is directory & recurse : do recurse
323 if ( fs::is_directory(itr->status()) )
327 CheckSyncDirectory( itr->string(), recursive, repair, checkAttributes, i_ignorefiles, attsModified, newfiles);
332 if (IsHandledFile(itr->string()))
335 for(std::vector<std::string>::iterator it_new = i_ignorefiles.begin(); it_new < i_ignorefiles.end(); ++it_new)
337 if((*it_new) == itr->string())
340 //Additional checking of attributes
343 CheckAttributes(repair,(*it_new),attsModified);
345 i_ignorefiles.erase(it_new);
349 if(!bfound && i_ignorefiles.size()>0 )
351 newfiles.push_back( itr->string() );
358 //=======================================================================
360 //=======================================================================
362 std::string TreeHandlerImageAdder::Synchronize(bool repair, bool checkAttributes)
364 std::vector<AddList> fileList;
365 std::vector<std::string> ignoreList;
366 std::vector<std::string> newFiles;
367 std::vector<std::string> attsModified;
368 std::stringstream mess;
369 std::vector<AddList>::iterator iter;
371 //Gets the list of added files
372 mSynchronizer->GetFileList(fileList,mCurrentDB);
374 std::vector<std::string>::iterator i;
375 //Actions to take if the user doesn't want to repair
378 //Iterates to see if they are in sync
379 for(iter=fileList.begin();iter!=fileList.end();++iter)
381 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
383 if((*iter).recursive=="0"){rec=false;}
384 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
387 //Add to message the result of new found files
388 mess<<"New Files Found: "<<newFiles.size()<<std::endl;
389 if(newFiles.size()>0)
391 mess<<"Filenames: "<<std::endl;
392 for(i=newFiles.begin();i!=newFiles.end();++i)
398 //Add to message the result of missing files
399 mess<<"Missing Files: "<<ignoreList.size()<<std::endl;
400 if(ignoreList.size()>0)
402 mess<<"Filenames: "<<std::endl;
403 for(i=ignoreList.begin();i!=ignoreList.end();++i)
409 //In the case that the user wants to check the attributes...
412 //... add to message the result of files that have been changed.
413 mess<<"Files with different attributes: "<<attsModified.size()<<std::endl;
414 if(attsModified.size()>0)
416 mess<<"Filenames: "<<std::endl;
417 for(i=attsModified.begin();i!=attsModified.end();++i)
426 //Actions to take if the user wants to repair
430 //Iterates to see if they are in sync
431 for(iter=fileList.begin();iter!=fileList.end();++iter)
433 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
435 if((*iter).recursive=="0"){rec=false;}
436 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
438 //For the new files, add them
439 for (i=newFiles.begin();i!=newFiles.end();++i)
441 if (IsHandledFile(*i))
443 std::stringstream removedOn;
445 mSynchronizer->InsertIgnoreFile((*iter).key,(*i),"0",removedOn.str(),mCurrentDB);
446 //Gets the number of files added
447 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",(*iter).key,mCurrentDB)).c_str());
449 std::stringstream out;
451 //Sets the new number of files
452 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",out.str(),"ADD_KEY",(*iter).key,mCurrentDB);
460 //Reports number of added files
461 mess<<"Files Added: "<<nf<<std::endl;
463 //Removes the necessary files and reports the results
464 if(ignoreList.size()>0)
467 mTreeHandler->LoadChildren(NULL,4);
468 for(i=ignoreList.begin();i!=ignoreList.end();++i)
470 FindNode(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",*i,node);
472 mTreeHandler->Remove(node);
475 mess<<"Files Removed: "<<ignoreList.size()<<std::endl;
476 //In the case that the user wants to check the attributes...
479 //... add to message the result of files that were modified.
480 mess<<"Files Modified: "<<attsModified.size()<<std::endl;
486 //=======================================================================
488 void TreeHandlerImageAdder::CheckAttributes(bool repair, std::string& file, std::vector<std::string>& attsModified)
490 std::map< std::string, std::string> attr;
491 mTreeHandler->GetTree().GetDescriptor().BuildAttributeMap(attr);
492 mReader.ReadAttributes(file,attr);
493 tree::LevelDescriptor::AttributeDescriptorListType adl= mTreeHandler->GetTree().GetAttributeDescriptorList(mTreeHandler->GetTree().GetNumberOfLevels()-1);
494 tree::LevelDescriptor::AttributeDescriptorListType::const_iterator a;
495 for (a = adl.begin();a!=adl.end();++a)
497 std::string databaseVal;
498 mTreeHandler->GetAttribute("Image","FullFileName",file,a->GetKey(),databaseVal);
499 std::string fileVal=attr.find(a->GetKey())->second;
500 if ( a->GetFlags()==0 && databaseVal == fileVal)
504 mTreeHandler->SetAttribute("Image",a->GetKey(),fileVal,"FullFileName", file);
506 attsModified.push_back(file);
513 //=======================================================================
516 void TreeHandlerImageAdder::FindNode(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
520 std::vector<tree::Node*>::iterator iter;
521 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end();++iter)
523 FindNode(*iter,level-1,searchParam,searchVal,node);
528 if(parent->GetAttribute(searchParam).compare(searchVal)==0)
536 void TreeHandlerImageAdder::SaveAs(const std::vector<std::string>& filenames, std::vector<vtkImageData *> i_images)
538 std::vector<std::string>::const_iterator it_file = filenames.begin();
539 std::vector<vtkImageData *>::iterator it_image = i_images.begin();
540 /* mWriter.CanWrite(".jpeg");
541 for(; it_file != filenames.end(); ++it_file, ++it_image)
542 mWriter.WriteImage(it_file->c_str(), (vtkImageData &)it_image);*/
545 //=======================================================================
546 void TreeHandlerImageAdder::FindNodePartial(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
550 std::vector<tree::Node*>::iterator iter;
551 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end() && node==0 ;++iter)
553 FindNodePartial(*iter,level-1,searchParam,searchVal,node);
558 if(parent->GetAttribute(searchParam).find(searchVal)<9000)
567 //=======================================================================
569 void TreeHandlerImageAdder::CopyFiles(const std::vector<std::string>& filenames, const std::string directory )
571 std::vector<std::string>::const_iterator i;
572 if(!boost::filesystem::exists(directory))
574 boost::filesystem::create_directory(boost::filesystem::path(directory));
575 mSynchronizer->InsertAddOp(directory,"0","0",mCurrentDB);
577 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","ADD_OPS","PATH",directory,mCurrentDB);
579 std::vector<std::string> newNames;
580 for(i=filenames.begin();i!=filenames.end();++i)
582 std::string dir=directory.c_str();
583 if(boost::filesystem::exists(*i) && (*i).find(dir)==std::string::npos)
586 last=(*i).find_last_of('/');
587 std::string f="\\"+(*i).substr(last+1);
590 std::stringstream out;
592 while(boost::filesystem::exists(out.str()))
595 out<<directory<<f.substr(0,f.size()-4)<<"("<<p<<")"<<f.substr(f.size()-4);
598 std::string result=out.str();
599 boost::filesystem::copy_file((*i),result);
601 //To update image database
602 mTreeHandler->SetAttribute("Image","FullFileName",result,"FullFileName", (*i));
604 //To update maintenance database
605 //1.Add the new path and increase number of children on new operation.
606 std::stringstream removedOn;
609 mSynchronizer->InsertIgnoreFile(addKey, result,"0",removedOn.str(),mCurrentDB);
610 //Gets the number of files added
611 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",addKey,mCurrentDB)).c_str());
613 std::stringstream fil;
615 //Sets the new number of files
616 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",addKey,mCurrentDB);
619 //2.Set the old path as removed and decrease number of children on old operation.
620 //Gets the old add key
621 std::string oldAddKey=mSynchronizer->GetAttribute("ADD_KEY","IGNORED_FILES","PATH",path,mCurrentDB);
622 //Sets the file as removed
623 mSynchronizer->SetAttribute("REMOVE","IGNORED_FILES","1","PATH = '"+path+"' AND ADD_KEY",oldAddKey,mCurrentDB);
624 //Gets the number of files added
625 files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",oldAddKey,mCurrentDB)).c_str());
628 //Sets the new number of files
629 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",oldAddKey,mCurrentDB);
636 //=======================================================================
638 void TreeHandlerImageAdder::DeleteDriveFromMainDB(const std::string& drive)
640 //Delete from local database and others
642 mTreeHandler->LoadChildren(NULL,4);
643 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
646 mTreeHandler->Remove(node);
648 mTreeHandler->LoadChildren(NULL,4);
649 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
653 //=======================================================================
655 void TreeHandlerImageAdder::DeleteDriveFromOtherDB(const std::string& drive)
657 //Delete from maintenance
658 mSynchronizer->RemoveEntries("ADD_OPS", "PATH", "LIKE", drive+"%");
659 mSynchronizer->RemoveEntries("IGNORED_FILES", "PATH", "LIKE", drive+"%");
662 //=======================================================================
663 void TreeHandlerImageAdder::EditField(tree::Node* node, const std::string& name, const std::string& key, const std::string& val)
665 node->SetAttribute(key,val);
666 mTreeHandler->SetAttribute(node,key,val);
669 //=======================================================================
670 void TreeHandlerImageAdder::GetAttributes(const std::vector<std::string>& params,
671 const std::string& filename,
672 std::vector<std::string>& results)
674 std::vector<std::string>::const_iterator i;
676 for(i=params.begin();i!=params.end();i++)
678 mTreeHandler->GetAttribute("Image","FullFileName",filename,*i,result);
679 results.push_back(result);
683 //=======================================================================
684 const std::string TreeHandlerImageAdder::isAttributeExist(const std::string i_attr)
686 return mTreeHandler->GetTree().isAttributeExist(i_attr);