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;
259 /// \TODO fix warning: unused variable lastModif
260 time_t lastModif=fs::last_write_time(dirpath);
262 fs::directory_iterator end_itr; // default construction yields past-the-end
263 for ( fs::directory_iterator itr( dirpath );
267 // If is directory & recurse : do recurse
268 if ( fs::is_directory(itr->status()) )
272 AddDirectoryRecursor( itr->string(), recursive, addKey);
277 std::string parent_id;
278 // tTest if directory (and only it) exists or not.
279 bool valid = mSynchronizer->isIndexed(itr->string());//true;//=mTimestampHandler->AddDirectory(dirpath, itr->string(), lastModif, time(0),mCurrentDB);
282 mProgress.IncNumberScannedFiles();
283 if (IsHandledFile(itr->string()))
285 mProgress.IncNumberHandledFiles();
286 AddFile( itr->string() );
287 //mTreeHandler->GetTopLevelNodeId("FullFileName",itr->string(),parent_id);
288 std::stringstream removedOn;
290 mSynchronizer->InsertIgnoreFile(addKey, itr->string(),"0",removedOn.str(),mCurrentDB);
293 mProgressSignal(mProgress);
294 if (mProgress.GetStop())
305 //=======================================================================
308 //=======================================================================
310 void TreeHandlerImageAdder::CheckSyncDirectory(const std::string &dirpath,
313 bool checkAttributes,
314 std::vector<std::string> &i_ignorefiles,
315 std::vector<std::string> & attsModified,
316 std::vector<std::string> & newfiles)
318 if ( !fs::exists( dirpath ) ) return;
319 fs::directory_iterator end_itr; // default construction yields past-the-end
321 for ( fs::directory_iterator itr( dirpath ); itr != end_itr; ++itr )
323 // If is directory & recurse : do recurse
324 if ( fs::is_directory(itr->status()) )
328 CheckSyncDirectory( itr->string(), recursive, repair, checkAttributes, i_ignorefiles, attsModified, newfiles);
333 if (IsHandledFile(itr->string()))
336 for(std::vector<std::string>::iterator it_new = i_ignorefiles.begin(); it_new < i_ignorefiles.end(); ++it_new)
338 if((*it_new) == itr->string())
341 //Additional checking of attributes
344 CheckAttributes(repair,(*it_new),attsModified);
346 i_ignorefiles.erase(it_new);
350 if(!bfound && i_ignorefiles.size()>0 )
352 newfiles.push_back( itr->string() );
359 //=======================================================================
361 //=======================================================================
363 std::string TreeHandlerImageAdder::Synchronize(bool repair, bool checkAttributes)
365 std::vector<AddList> fileList;
366 std::vector<std::string> ignoreList;
367 std::vector<std::string> newFiles;
368 std::vector<std::string> attsModified;
369 std::stringstream mess;
370 std::vector<AddList>::iterator iter;
372 //Gets the list of added files
373 mSynchronizer->GetFileList(fileList,mCurrentDB);
375 std::vector<std::string>::iterator i;
376 //Actions to take if the user doesn't want to repair
379 //Iterates to see if they are in sync
380 for(iter=fileList.begin();iter!=fileList.end();++iter)
382 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
384 if((*iter).recursive=="0"){rec=false;}
385 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
388 //Add to message the result of new found files
389 mess<<"New Files Found: "<<newFiles.size()<<std::endl;
390 if(newFiles.size()>0)
392 mess<<"Filenames: "<<std::endl;
393 for(i=newFiles.begin();i!=newFiles.end();++i)
399 //Add to message the result of missing files
400 mess<<"Missing Files: "<<ignoreList.size()<<std::endl;
401 if(ignoreList.size()>0)
403 mess<<"Filenames: "<<std::endl;
404 for(i=ignoreList.begin();i!=ignoreList.end();++i)
410 //In the case that the user wants to check the attributes...
413 //... add to message the result of files that have been changed.
414 mess<<"Files with different attributes: "<<attsModified.size()<<std::endl;
415 if(attsModified.size()>0)
417 mess<<"Filenames: "<<std::endl;
418 for(i=attsModified.begin();i!=attsModified.end();++i)
427 //Actions to take if the user wants to repair
431 //Iterates to see if they are in sync
432 for(iter=fileList.begin();iter!=fileList.end();++iter)
434 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
436 if((*iter).recursive=="0"){rec=false;}
437 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
439 //For the new files, add them
440 for (i=newFiles.begin();i!=newFiles.end();++i)
442 if (IsHandledFile(*i))
444 std::stringstream removedOn;
446 mSynchronizer->InsertIgnoreFile((*iter).key,(*i),"0",removedOn.str(),mCurrentDB);
447 //Gets the number of files added
448 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",(*iter).key,mCurrentDB)).c_str());
450 std::stringstream out;
452 //Sets the new number of files
453 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",out.str(),"ADD_KEY",(*iter).key,mCurrentDB);
461 //Reports number of added files
462 mess<<"Files Added: "<<nf<<std::endl;
464 //Removes the necessary files and reports the results
465 if(ignoreList.size()>0)
468 mTreeHandler->LoadChildren(NULL,4);
469 for(i=ignoreList.begin();i!=ignoreList.end();++i)
471 FindNode(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",*i,node);
473 mTreeHandler->Remove(node);
476 mess<<"Files Removed: "<<ignoreList.size()<<std::endl;
477 //In the case that the user wants to check the attributes...
480 //... add to message the result of files that were modified.
481 mess<<"Files Modified: "<<attsModified.size()<<std::endl;
487 //=======================================================================
489 void TreeHandlerImageAdder::CheckAttributes(bool repair, std::string& file, std::vector<std::string>& attsModified)
491 std::map< std::string, std::string> attr;
492 mTreeHandler->GetTree().GetDescriptor().BuildAttributeMap(attr);
493 mReader.ReadAttributes(file,attr);
494 tree::LevelDescriptor::AttributeDescriptorListType adl= mTreeHandler->GetTree().GetAttributeDescriptorList(mTreeHandler->GetTree().GetNumberOfLevels()-1);
495 tree::LevelDescriptor::AttributeDescriptorListType::const_iterator a;
496 for (a = adl.begin();a!=adl.end();++a)
498 std::string databaseVal;
499 mTreeHandler->GetAttribute("Image","FullFileName",file,a->GetKey(),databaseVal);
500 std::string fileVal=attr.find(a->GetKey())->second;
501 if ( a->GetFlags()==0 && databaseVal == fileVal)
505 mTreeHandler->SetAttribute("Image",a->GetKey(),fileVal,"FullFileName", file);
507 attsModified.push_back(file);
514 //=======================================================================
517 void TreeHandlerImageAdder::FindNode(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
521 std::vector<tree::Node*>::iterator iter;
522 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end();++iter)
524 FindNode(*iter,level-1,searchParam,searchVal,node);
529 if(parent->GetAttribute(searchParam).compare(searchVal)==0)
537 void TreeHandlerImageAdder::SaveAs(const std::vector<std::string>& filenames, std::vector<vtkImageData *> i_images)
539 std::vector<std::string>::const_iterator it_file = filenames.begin();
540 std::vector<vtkImageData *>::iterator it_image = i_images.begin();
541 /* mWriter.CanWrite(".jpeg");
542 for(; it_file != filenames.end(); ++it_file, ++it_image)
543 mWriter.WriteImage(it_file->c_str(), (vtkImageData &)it_image);*/
546 //=======================================================================
547 void TreeHandlerImageAdder::FindNodePartial(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
551 std::vector<tree::Node*>::iterator iter;
552 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end() && node==0 ;++iter)
554 FindNodePartial(*iter,level-1,searchParam,searchVal,node);
559 if(parent->GetAttribute(searchParam).find(searchVal)<9000)
568 //=======================================================================
570 void TreeHandlerImageAdder::CopyFiles(const std::vector<std::string>& filenames, const std::string directory )
572 std::vector<std::string>::const_iterator i;
573 if(!boost::filesystem::exists(directory))
575 boost::filesystem::create_directory(boost::filesystem::path(directory));
576 mSynchronizer->InsertAddOp(directory,"0","0",mCurrentDB);
578 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","ADD_OPS","PATH",directory,mCurrentDB);
580 std::vector<std::string> newNames;
581 for(i=filenames.begin();i!=filenames.end();++i)
583 std::string dir=directory.c_str();
584 if(boost::filesystem::exists(*i) && (*i).find(dir)==std::string::npos)
587 last=(*i).find_last_of('/');
588 std::string f="\\"+(*i).substr(last+1);
591 std::stringstream out;
593 while(boost::filesystem::exists(out.str()))
596 out<<directory<<f.substr(0,f.size()-4)<<"("<<p<<")"<<f.substr(f.size()-4);
599 std::string result=out.str();
600 boost::filesystem::copy_file((*i),result);
602 //To update image database
603 mTreeHandler->SetAttribute("Image","FullFileName",result,"FullFileName", (*i));
605 //To update maintenance database
606 //1.Add the new path and increase number of children on new operation.
607 std::stringstream removedOn;
610 mSynchronizer->InsertIgnoreFile(addKey, result,"0",removedOn.str(),mCurrentDB);
611 //Gets the number of files added
612 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",addKey,mCurrentDB)).c_str());
614 std::stringstream fil;
616 //Sets the new number of files
617 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",addKey,mCurrentDB);
620 //2.Set the old path as removed and decrease number of children on old operation.
621 //Gets the old add key
622 std::string oldAddKey=mSynchronizer->GetAttribute("ADD_KEY","IGNORED_FILES","PATH",path,mCurrentDB);
623 //Sets the file as removed
624 mSynchronizer->SetAttribute("REMOVE","IGNORED_FILES","1","PATH = '"+path+"' AND ADD_KEY",oldAddKey,mCurrentDB);
625 //Gets the number of files added
626 files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",oldAddKey,mCurrentDB)).c_str());
629 //Sets the new number of files
630 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",oldAddKey,mCurrentDB);
637 //=======================================================================
639 void TreeHandlerImageAdder::DeleteDriveFromMainDB(const std::string& drive)
641 //Delete from local database and others
643 mTreeHandler->LoadChildren(NULL,4);
644 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
647 mTreeHandler->Remove(node);
649 mTreeHandler->LoadChildren(NULL,4);
650 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
654 //=======================================================================
656 void TreeHandlerImageAdder::DeleteDriveFromOtherDB(const std::string& drive)
658 //Delete from maintenance
659 mSynchronizer->RemoveEntries("ADD_OPS", "PATH", "LIKE", drive+"%");
660 mSynchronizer->RemoveEntries("IGNORED_FILES", "PATH", "LIKE", drive+"%");
663 //=======================================================================
664 void TreeHandlerImageAdder::EditField(tree::Node* node, const std::string& name, const std::string& key, const std::string& val)
666 node->SetAttribute(key,val);
667 mTreeHandler->SetAttribute(node,key,val);
670 //=======================================================================
671 void TreeHandlerImageAdder::GetAttributes(const std::vector<std::string>& params,
672 const std::string& filename,
673 std::vector<std::string>& results)
675 std::vector<std::string>::const_iterator i;
677 for(i=params.begin();i!=params.end();i++)
679 mTreeHandler->GetAttribute("Image","FullFileName",filename,*i,result);
680 results.push_back(result);
684 //=======================================================================
685 const std::string TreeHandlerImageAdder::isAttributeExist(const std::string i_attr)
687 return mTreeHandler->GetTree().isAttributeExist(i_attr);