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);
226 mProgress.IncNumberScannedFiles();
227 boost::algorithm::replace_all( itr->string(),
228 INVALID_FILE_SEPARATOR ,
229 VALID_FILE_SEPARATOR);
230 i_sc.ReadAttributes(itr->string(),attr);
231 // mTreeHandler->GetTopLevelNodeId("FullFileName",itr->string(),parent_id);
232 mTreeHandler->AddBranch(attr);
233 mProgress.IncNumberHandledFiles();
234 std::stringstream removedOn;
236 mSynchronizer->InsertIgnoreFile(addKey, itr->string(),"0",removedOn.str(),mCurrentDB);
239 mProgressSignal(mProgress);
240 if (mProgress.GetStop())
251 //=====================================================================
252 void TreeHandlerImageAdder::AddDirectoryRecursor(const std::string &dirpath,
254 const std::string &addKey)
256 GimmickDebugMessage(4,"Scanning '"<<dirpath<<"'"<<std::endl);
257 mProgress.IncNumberScannedDirs();
259 if ( !fs::exists( dirpath ) ) return;
260 time_t lastModif=fs::last_write_time(dirpath);
263 fs::directory_iterator end_itr; // default construction yields past-the-end
264 for ( fs::directory_iterator itr( dirpath );
268 // If is directory & recurse : do recurse
269 if ( fs::is_directory(itr->status()) )
273 AddDirectoryRecursor( itr->string(), recursive, addKey);
278 std::string parent_id;
279 // tTest if directory (and only it) exists or not.
280 bool valid = mSynchronizer->isIndexed(itr->string());//true;//=mTimestampHandler->AddDirectory(dirpath, itr->string(), lastModif, time(0),mCurrentDB);
283 mProgress.IncNumberScannedFiles();
284 if (IsHandledFile(itr->string()))
286 mProgress.IncNumberHandledFiles();
287 AddFile( itr->string() );
288 //mTreeHandler->GetTopLevelNodeId("FullFileName",itr->string(),parent_id);
289 std::stringstream removedOn;
291 mSynchronizer->InsertIgnoreFile(addKey, itr->string(),"0",removedOn.str(),mCurrentDB);
294 mProgressSignal(mProgress);
295 if (mProgress.GetStop())
306 //=======================================================================
309 //=======================================================================
311 void TreeHandlerImageAdder::CheckSyncDirectory(const std::string &dirpath,
314 bool checkAttributes,
315 std::vector<std::string> &i_ignorefiles,
316 std::vector<std::string> & attsModified,
317 std::vector<std::string> & newfiles)
319 if ( !fs::exists( dirpath ) ) return;
320 fs::directory_iterator end_itr; // default construction yields past-the-end
322 for ( fs::directory_iterator itr( dirpath ); itr != end_itr; ++itr )
324 // If is directory & recurse : do recurse
325 if ( fs::is_directory(itr->status()) )
329 CheckSyncDirectory( itr->string(), recursive, repair, checkAttributes, i_ignorefiles, attsModified, newfiles);
334 if (IsHandledFile(itr->string()))
337 for(std::vector<std::string>::iterator it_new = i_ignorefiles.begin(); it_new < i_ignorefiles.end(); ++it_new)
339 if((*it_new) == itr->string())
342 //Additional checking of attributes
345 CheckAttributes(repair,(*it_new),attsModified);
347 i_ignorefiles.erase(it_new);
351 if(!bfound && i_ignorefiles.size()>0 )
353 newfiles.push_back( itr->string() );
360 //=======================================================================
362 //=======================================================================
364 std::string TreeHandlerImageAdder::Synchronize(bool repair, bool checkAttributes)
366 std::vector<AddList> fileList;
367 std::vector<std::string> ignoreList;
368 std::vector<std::string> newFiles;
369 std::vector<std::string> attsModified;
370 std::stringstream mess;
371 std::vector<AddList>::iterator iter;
373 //Gets the list of added files
374 mSynchronizer->GetFileList(fileList,mCurrentDB);
376 std::vector<std::string>::iterator i;
377 //Actions to take if the user doesn't want to repair
380 //Iterates to see if they are in sync
381 for(iter=fileList.begin();iter!=fileList.end();++iter)
383 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
385 if((*iter).recursive=="0"){rec=false;}
386 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
389 //Add to message the result of new found files
390 mess<<"New Files Found: "<<newFiles.size()<<std::endl;
391 if(newFiles.size()>0)
393 mess<<"Filenames: "<<std::endl;
394 for(i=newFiles.begin();i!=newFiles.end();++i)
400 //Add to message the result of missing files
401 mess<<"Missing Files: "<<ignoreList.size()<<std::endl;
402 if(ignoreList.size()>0)
404 mess<<"Filenames: "<<std::endl;
405 for(i=ignoreList.begin();i!=ignoreList.end();++i)
411 //In the case that the user wants to check the attributes...
414 //... add to message the result of files that have been changed.
415 mess<<"Files with different attributes: "<<attsModified.size()<<std::endl;
416 if(attsModified.size()>0)
418 mess<<"Filenames: "<<std::endl;
419 for(i=attsModified.begin();i!=attsModified.end();++i)
428 //Actions to take if the user wants to repair
432 //Iterates to see if they are in sync
433 for(iter=fileList.begin();iter!=fileList.end();++iter)
435 mSynchronizer->GetIgnoredFiles((*iter).key,ignoreList);
437 if((*iter).recursive=="0"){rec=false;}
438 CheckSyncDirectory((*iter).path,rec,repair,checkAttributes,ignoreList,attsModified,newFiles);
440 //For the new files, add them
441 for (i=newFiles.begin();i!=newFiles.end();++i)
443 if (IsHandledFile(*i))
445 std::stringstream removedOn;
447 mSynchronizer->InsertIgnoreFile((*iter).key,(*i),"0",removedOn.str(),mCurrentDB);
448 //Gets the number of files added
449 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",(*iter).key,mCurrentDB)).c_str());
451 std::stringstream out;
453 //Sets the new number of files
454 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",out.str(),"ADD_KEY",(*iter).key,mCurrentDB);
462 //Reports number of added files
463 mess<<"Files Added: "<<nf<<std::endl;
465 //Removes the necessary files and reports the results
466 if(ignoreList.size()>0)
469 mTreeHandler->LoadChildren(NULL,4);
470 for(i=ignoreList.begin();i!=ignoreList.end();++i)
472 FindNode(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",*i,node);
474 mTreeHandler->Remove(node);
477 mess<<"Files Removed: "<<ignoreList.size()<<std::endl;
478 //In the case that the user wants to check the attributes...
481 //... add to message the result of files that were modified.
482 mess<<"Files Modified: "<<attsModified.size()<<std::endl;
488 //=======================================================================
490 void TreeHandlerImageAdder::CheckAttributes(bool repair, std::string& file, std::vector<std::string>& attsModified)
492 std::map< std::string, std::string> attr;
493 mTreeHandler->GetTree().GetDescriptor().BuildAttributeMap(attr);
494 mReader.ReadAttributes(file,attr);
495 tree::LevelDescriptor::AttributeDescriptorListType adl= mTreeHandler->GetTree().GetAttributeDescriptorList(mTreeHandler->GetTree().GetNumberOfLevels()-1);
496 tree::LevelDescriptor::AttributeDescriptorListType::const_iterator a;
497 for (a = adl.begin();a!=adl.end();++a)
499 std::string databaseVal;
500 mTreeHandler->GetAttribute("Image","FullFileName",file,a->GetKey(),databaseVal);
501 std::string fileVal=attr.find(a->GetKey())->second;
502 if ( a->GetFlags()==0 && databaseVal == fileVal)
506 mTreeHandler->SetAttribute("Image",a->GetKey(),fileVal,"FullFileName", file);
508 attsModified.push_back(file);
515 //=======================================================================
518 void TreeHandlerImageAdder::FindNode(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
522 std::vector<tree::Node*>::iterator iter;
523 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end();++iter)
525 FindNode(*iter,level-1,searchParam,searchVal,node);
530 if(parent->GetAttribute(searchParam).compare(searchVal)==0)
538 void TreeHandlerImageAdder::SaveAs(const std::vector<std::string>& filenames, std::vector<vtkImageData *> i_images)
540 std::vector<std::string>::const_iterator it_file = filenames.begin();
541 std::vector<vtkImageData *>::iterator it_image = i_images.begin();
542 /* mWriter.CanWrite(".jpeg");
543 for(; it_file != filenames.end(); ++it_file, ++it_image)
544 mWriter.WriteImage(it_file->c_str(), (vtkImageData &)it_image);*/
547 //=======================================================================
548 void TreeHandlerImageAdder::FindNodePartial(tree::Node* parent, int level, const std::string& searchParam, const std::string& searchVal, tree::Node*& node)
552 std::vector<tree::Node*>::iterator iter;
553 for(iter=parent->GetChildrenList().begin();iter!=parent->GetChildrenList().end() && node==0 ;++iter)
555 FindNodePartial(*iter,level-1,searchParam,searchVal,node);
560 if(parent->GetAttribute(searchParam).find(searchVal)<9000)
569 //=======================================================================
571 void TreeHandlerImageAdder::CopyFiles(const std::vector<std::string>& filenames, const std::string directory )
573 std::vector<std::string>::const_iterator i;
574 if(!boost::filesystem::exists(directory))
576 boost::filesystem::create_directory(boost::filesystem::path(directory));
577 mSynchronizer->InsertAddOp(directory,"0","0",mCurrentDB);
579 std::string addKey=mSynchronizer->GetAttribute("ADD_KEY","ADD_OPS","PATH",directory,mCurrentDB);
581 std::vector<std::string> newNames;
582 for(i=filenames.begin();i!=filenames.end();++i)
584 std::string dir=directory.c_str();
585 if(boost::filesystem::exists(*i) && (*i).find(dir)==std::string::npos)
588 last=(*i).find_last_of('/');
589 std::string f="\\"+(*i).substr(last+1);
592 std::stringstream out;
594 while(boost::filesystem::exists(out.str()))
597 out<<directory<<f.substr(0,f.size()-4)<<"("<<p<<")"<<f.substr(f.size()-4);
600 std::string result=out.str();
601 boost::filesystem::copy_file((*i),result);
603 //To update image database
604 mTreeHandler->SetAttribute("Image","FullFileName",result,"FullFileName", (*i));
606 //To update maintenance database
607 //1.Add the new path and increase number of children on new operation.
608 std::stringstream removedOn;
611 mSynchronizer->InsertIgnoreFile(addKey, result,"0",removedOn.str(),mCurrentDB);
612 //Gets the number of files added
613 int files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",addKey,mCurrentDB)).c_str());
615 std::stringstream fil;
617 //Sets the new number of files
618 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",addKey,mCurrentDB);
621 //2.Set the old path as removed and decrease number of children on old operation.
622 //Gets the old add key
623 std::string oldAddKey=mSynchronizer->GetAttribute("ADD_KEY","IGNORED_FILES","PATH",path,mCurrentDB);
624 //Sets the file as removed
625 mSynchronizer->SetAttribute("REMOVE","IGNORED_FILES","1","PATH = '"+path+"' AND ADD_KEY",oldAddKey,mCurrentDB);
626 //Gets the number of files added
627 files=atoi((mSynchronizer->GetAttribute("FILES_ADDED","ADD_OPS","ADD_KEY",oldAddKey,mCurrentDB)).c_str());
630 //Sets the new number of files
631 mSynchronizer->SetAttribute("FILES_ADDED","ADD_OPS",fil.str(),"ADD_KEY",oldAddKey,mCurrentDB);
638 //=======================================================================
640 void TreeHandlerImageAdder::DeleteDriveFromMainDB(const std::string& drive)
642 //Delete from local database and others
644 mTreeHandler->LoadChildren(NULL,4);
645 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
648 mTreeHandler->Remove(node);
650 mTreeHandler->LoadChildren(NULL,4);
651 FindNodePartial(mTreeHandler->GetTree().GetChildrenList()[0],3,"FullFileName",drive,node);
655 //=======================================================================
657 void TreeHandlerImageAdder::DeleteDriveFromOtherDB(const std::string& drive)
659 //Delete from maintenance
660 mSynchronizer->RemoveEntries("ADD_OPS", "PATH", "LIKE", drive+"%");
661 mSynchronizer->RemoveEntries("IGNORED_FILES", "PATH", "LIKE", drive+"%");
664 //=======================================================================
665 void TreeHandlerImageAdder::EditField(tree::Node* node, const std::string& name, const std::string& key, const std::string& val)
667 node->SetAttribute(key,val);
668 mTreeHandler->SetAttribute(node,key,val);
671 //=======================================================================
672 void TreeHandlerImageAdder::GetAttributes(const std::vector<std::string>& params,
673 const std::string& filename,
674 std::vector<std::string>& results)
676 std::vector<std::string>::const_iterator i;
678 for(i=params.begin();i!=params.end();i++)
680 mTreeHandler->GetAttribute("Image","FullFileName",filename,*i,result);
681 results.push_back(result);
685 //=======================================================================
686 const std::string TreeHandlerImageAdder::isAttributeExist(const std::string i_attr)
688 return mTreeHandler->GetTree().isAttributeExist(i_attr);