creaImageIOGimmick.cpp

Go to the documentation of this file.
00001 
00002 #include <creaImageIOGimmick.h>
00003 #include <creaImageIOSystem.h>
00004 #include <boost/filesystem.hpp>
00005 #include <boost/algorithm/string.hpp>
00006 
00007 //#include "io.h"
00008 #ifndef PATH_MAX // If not defined yet : do it 
00009 #  define PATH_MAX 2048
00010 #endif
00011 #include <creaImageIOGimmick.h>
00012 
00013 #ifdef _DEBUG
00014 #define new DEBUG_NEW
00015 #endif
00016 
00017 
00018 namespace creaImageIO
00019 {
00020   //==============================================================
00021   Gimmick::Gimmick()
00022     : mImageAdder(0)
00023   {    
00024   RegisterGimmickMessageTypes();
00025         mSettings=0;
00026         mSynchronizer=0;
00027         mLocalDescpName = "localdatabase_Descriptor.dscp";
00028         mLocalDBName = "Local database";
00029   }
00030   //==============================================================
00031 
00032 
00033   //==============================================================
00034   Gimmick::~Gimmick()
00035   {
00036 
00037          if(mSettings!=0)
00038           {
00039                 mSettings->writeSettingsFile();
00040                 delete mSettings;
00041           }
00042         if(mSynchronizer!=0)
00043           {
00044                 delete mSynchronizer;
00045           }
00046   }
00047   //==============================================================
00048   
00049   //==============================================================
00050   void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
00051   {
00052           mLocalDescpName = i_namedescp;
00053           mLocalDBName = i_namedb;
00054           Initialize();
00055   }
00056 
00057   //==============================================================
00058   void Gimmick::Initialize()
00059   {
00060         std::string i_nameDB = mLocalDBName;
00061     // Create the UserSettings dir if does not exist
00062     CreateUserSettingsDirectory();
00063     // Sets the current directory to the home dir
00064     mCurrentDirectory =  GetHomeDirectory();
00065     mSynchronizer= new Synchronizer(GetUserSettingsDirectory()+"share/creaImageIO/");
00066 
00067     mSettings  = new Settings(mCurrentDirectory);
00068         
00069     std::string dbpath = GetLocalDatabasePath();
00070 
00071     // Create or open local database
00072     std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
00073         
00074     boost::algorithm::replace_all( dpath,
00075                                    INVALID_FILE_SEPARATOR , 
00076                                    VALID_FILE_SEPARATOR);
00077     mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
00078     // Add it to the TreeHandlerMap
00079     mTreeHandlerMap[i_nameDB] = mLocalDatabase;
00080     
00081     //Add additional DB from user Settings
00082     addDBSettings();    
00083   }
00084 
00086    // add DB to TreeHandler Map                                         //
00087    // @param i_name : DB name                                           //
00088    // @param i_location : DB location                                   //
00089    // return : -                                                        //
00091  void Gimmick::addDB(const std::string &i_name, 
00092                      const std::string &i_location)
00093         {
00094                 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
00095                 {
00096                         mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
00097                         mTreeHandlerMap[i_name]->Open(true);
00098                         mSettings->addDB(i_location);
00099                 }
00100         }
00101 
00103   // create a DB from a attributes descriptor file for medical images      //
00104   // @param i_name : DB name                                                                                       //
00105   // @param i_locDesc : location of descriptor file                                                //
00106   // @param i_locDB : location of DB                                                                       //
00107   // return : the SQLiteTreeHandler object on DB                                                   //
00109         SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
00110                                              const std::string &i_locDesc,
00111                                              const std::string &i_locDB)
00112   {
00113      SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
00114     // Create or open local database
00115     if (! boost::filesystem::exists(i_locDB) )
00116      {
00117          std::string mess = "Local database '";
00118          mess += i_locDB;
00119          mess += "' does not exist : creating it";
00120          GimmickMessage(1,mess<<std::endl);
00121          
00122                  // CREATING DB STRUCTURE
00123          sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
00124          if ( ! sqlTreeH->Create(true) )
00125          {
00126                 GimmickError("ERROR CREATING '"<<i_locDB<<"'");
00127          }
00128          sqlTreeH->SetAttribute(0,"Name",i_name);
00129          }
00130          else 
00131          {
00133                 
00134                 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
00135                 if ( !sqlTreeH->Open(true) )
00136                 {
00137                         GimmickError("ERROR OPENING '"<<i_locDB<<"'");
00138                 }
00139         }
00140         return sqlTreeH;
00141   }
00142 
00143   //==============================================================
00144   void Gimmick::Finalize()
00145   {
00146           if(mTreeHandlerMap.size() >0)
00147           {
00148                 // delete SQLiteTreeHandler Object
00149                 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
00150                                                                                                         it!= mTreeHandlerMap.end(); 
00151                                                         ++it)
00152                 {
00153                         delete it->second;
00154                 }
00155           }
00156   }
00157   //==============================================================
00158 
00159   //================================================================
00160   // file separator
00161 #if defined(_WIN32)
00162 #define VALID_FILE_SEPARATOR "\\"
00163 #define INVALID_FILE_SEPARATOR "/"
00164 #else
00165 #define INVALID_FILE_SEPARATOR "\\"
00166 #define VALID_FILE_SEPARATOR "/"
00167 #endif
00168   //================================================================
00169 
00170   //================================================================
00171   const std::string& Gimmick::GetHomeDirectory()
00172   {
00173     if (mHomeDirectory.size()==0) 
00174       {
00175 #if defined(__GNUC__)
00176         mHomeDirectory = getenv("HOME");
00177 #elif defined(_WIN32)
00178         mHomeDirectory = getenv("USERPROFILE");
00179 #endif
00180       }
00181     return mHomeDirectory;
00182   }
00183   //================================================================
00184   const std::string& Gimmick::GetUserSettingsDirectory()
00185   {
00186     if (mUserSettingsDirectory.size()==0) 
00187       {
00188         mUserSettingsDirectory = GetHomeDirectory();
00189         mUserSettingsDirectory += "/.creaImageIO/";
00190         boost::algorithm::replace_all( mUserSettingsDirectory, 
00191                                        INVALID_FILE_SEPARATOR , 
00192                                        VALID_FILE_SEPARATOR);
00193       }
00194     return mUserSettingsDirectory;
00195   }
00196   //================================================================
00197 
00198 
00199   //================================================================
00200   const std::string& Gimmick::GetLocalDatabasePath()
00201   {
00202     if (mLocalDatabasePath.size()==0) 
00203       {
00204         mLocalDatabasePath = GetUserSettingsDirectory();
00205         mLocalDatabasePath += "share/creaImageIO/";
00206         mLocalDatabasePath += mLocalDBName;
00207         mLocalDatabasePath +=".sqlite3";
00208         boost::algorithm::replace_all( mLocalDatabasePath,
00209                                        INVALID_FILE_SEPARATOR , 
00210                                        VALID_FILE_SEPARATOR);
00211       }
00212     return mLocalDatabasePath;    
00213   }
00214 
00215   //========================================================================
00216 
00217   //========================================================================
00218   void Gimmick::CreateUserSettingsDirectory()
00219   {
00220           
00221          // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
00222          //     boost::algorithm::replace_all( st, 
00223                 //                     INVALID_FILE_SEPARATOR , 
00224                 //                     VALID_FILE_SEPARATOR);
00225                 //const boost::filesystem::path mpath(st);
00226 //C:\Documents and Settings\cervenansky\.gimmick");
00227           //if ( !boost::filesystem::exists( path ) )             return ;
00228          //  boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
00229          //  for ( boost::filesystem::directory_iterator itr( path );  itr != end_itr;  ++itr )
00230          // {
00232                 //      if ( boost::filesystem::is_directory(itr->status()) )
00233                 //      return;
00234          //  }
00235 
00236           //JCP settings dir 02/10/2009
00237           const std::string settingsdirectory = GetUserSettingsDirectory();
00238                 //boost::algorithm::replace_all( mUserSettingsDirectory, 
00239                                 //       INVALID_FILE_SEPARATOR , 
00240                                 //       VALID_FILE_SEPARATOR);
00241 ;//("E:\frederic");
00242                   //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
00243                 bool isdir = false;
00244            isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
00245     if (! isdir )
00246       {
00247         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
00248                        << "does not exist : creating it"<<std::endl);
00249         
00250         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
00251           {
00252             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
00253           }
00254       }
00255 
00256         std::string setDir=GetUserSettingsDirectory();
00257         boost::algorithm::replace_all( setDir,
00258                                        INVALID_FILE_SEPARATOR , 
00259                                        VALID_FILE_SEPARATOR);
00260         setDir+="share/";
00261         boost::filesystem::create_directory( setDir );
00262         setDir+="creaImageIO/";
00263         boost::filesystem::create_directory( setDir );
00264         setDir+=mLocalDescpName;
00265 
00266         if(!boost::filesystem::is_regular(setDir))
00267         {
00268                 char name[PATH_MAX];
00269                 crea::System::GetAppPath(name,PATH_MAX);
00270                 std::cout<<name<<std::endl;
00271                 
00272                 std::string path=name;
00273                 path=path.substr(0,path.size()-1);
00274                 path=path.substr(0,path.find_last_of("/"));
00275                 //Creating directories
00276 
00277 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
00278                 
00279 #if defined(_WIN32)             
00280                 path+="/bin/share/creaImageIO/";
00281 #endif
00282 
00283 #if defined (LINUX)
00284                 path+="/../share/creaImageIO/";
00285 #endif  
00286 #if defined(__APPLE__)
00287                 path+="/../../../../share/creaImageIO/";
00288 #endif 
00289 
00290 
00291 path+= mLocalDescpName;
00292                 
00293                 std::cout <<"From: " << path   <<std::endl;
00294                 std::cout <<"To: "   << setDir <<std::endl;
00295                 boost::algorithm::replace_all(  path,
00296                                                 INVALID_FILE_SEPARATOR , 
00297                                                 VALID_FILE_SEPARATOR);
00298                 boost::filesystem::copy_file(path,setDir);
00299         }
00300           
00301   }
00302   //========================================================================
00303 
00304 
00305   //========================================================================
00307   void Gimmick::SetMessageLevel(int l)
00308   {
00309     SetGimmickMessageLevel(l);
00310   }
00311   //========================================================================
00312 
00313   //========================================================================
00315   void Gimmick::SetDebugMessageLevel(int l)
00316   {
00317     SetGimmickDebugMessageLevel(l);
00318   }
00319   //========================================================================
00320 
00321   //========================================================================
00323   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
00324   {  
00325     TreeHandlerMapType::const_iterator i;
00326     i = GetTreeHandlerMap().find(name);
00327     if ( i == GetTreeHandlerMap().end() )
00328       {
00329         GimmickError("TreeHandler '"<<name<<"' does not exist");
00330       }
00331     return i->second;
00332   }
00333 
00334   //========================================================================
00336   void Gimmick::AddFiles(const std::string& d, 
00337                         const std::vector<std::string>& filenames)
00338   {
00339     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
00340  
00341         mImageAdder.SetCurrentDatabase(d);
00342         mImageAdder.SetTreeHandler(GetTreeHandler(d));
00343         mImageAdder.SetSynchronizer(mSynchronizer);
00344         mImageAdder.AddFiles(filenames);        
00345   }
00346   //========================================================================
00347 
00348   //========================================================================
00350   void Gimmick::AddDir(const std::string& d, const std::string& f, 
00351                        bool recurse)
00352   {
00353         GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
00354                          <<recurse<<std::endl);
00355 
00356         TreeHandler * handler=GetTreeHandler(d);
00357         mImageAdder.SetCurrentDatabase(d);
00358         mImageAdder.SetTreeHandler(handler);
00359         mImageAdder.SetSynchronizer(mSynchronizer);
00360         mImageAdder.AddDirectory(f,recurse);  
00361   }
00362 
00363   //========================================================================
00364 
00365   //========================================================================
00366   void Gimmick::RemoveFile(const std::string& d, 
00367                            tree::Node* node)
00368   {
00369           mImageAdder.SetCurrentDatabase(d);
00370           mImageAdder.SetSynchronizer(mSynchronizer);
00371           mImageAdder.RemoveFile(node);
00372   }
00373   //========================================================================
00374 
00375   //void Gimmick::Anonymize(std::vector<std::string>i_files)  {  }
00376   //========================================================================
00377  
00378   void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
00379   {
00380           TreeHandler * handler=GetTreeHandler(d);
00381           mImageAdder.SetCurrentDatabase(d);
00382           mImageAdder.SetTreeHandler(handler);
00383           mImageAdder.SetSynchronizer(mSynchronizer);
00384           mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
00385   }
00386 
00387   //========================================================================
00388  
00389   std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
00390   {
00391           TreeHandler * handler=GetTreeHandler(d);
00392           mImageAdder.SetCurrentDatabase(d);
00393           mImageAdder.SetTreeHandler(handler);
00394           mImageAdder.SetSynchronizer(mSynchronizer);
00395           return mImageAdder.Synchronize(repair, checkAttributes);
00396   }
00397 
00398   //========================================================================
00400   void Gimmick::Print(const std::string& d)
00401   {
00402     GetTreeHandler(d)->GetTree().Print();
00403   }
00404   //========================================================================
00405 
00406   void Gimmick::GetSetting(const std::string& name, std::string& value)
00407   {
00408     value = mSettings->getValue(name);
00409   }
00410   //========================================================================
00411 
00412   //========================================================================
00413 
00414   void Gimmick::GetAttributes(const std::string& d, 
00415                         const std::string& filename, 
00416                         const std::vector<std::string>& params, 
00417                         std::vector<std::string>& results)
00418   {
00419           TreeHandler * handler=GetTreeHandler(d);
00420           mImageAdder.SetCurrentDatabase(d);
00421           mImageAdder.SetTreeHandler(handler);
00422           mImageAdder.SetSynchronizer(mSynchronizer);
00423           mImageAdder.GetAttributes(params, filename, results);
00424   }
00425   //========================================================================
00426 
00427   //========================================================================
00428   // get attributes values from database  for a given file from database 
00429   //========================================================================
00430    void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
00431   {
00432            if (i_attr.inside.size() > 0)
00433            {
00434                    std::map<std::string, std::string> map_attr;
00435                    TreeHandler * handler=GetTreeHandler(i_attr.db);
00436                    handler->getAllAttributes(filename, map_attr);
00437                    if(i_attr.inside.front() == "ALL") // we  take all values
00438                    {
00439                            std::map<std::string, std::string>::iterator it = map_attr.begin();
00440                            for(; it != map_attr.end(); it++)
00441                                    i_res[it->first] = it->second;
00442                    }
00443                    else
00444                    {
00445                             std::vector<std::string>::iterator it = i_attr.inside.begin();
00446                             for(; it != i_attr.inside.end(); it++)
00447                                    i_res[(*it)] = map_attr[(*it)];
00448                    }
00449            }
00450   }
00451 
00452 
00453   //========================================================================
00454 
00455   void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
00456   {
00457           mSettings->updateSetting(name,value);
00458           mSettings->writeSettingsFile();
00459   }
00460   //========================================================================
00461 
00462   void Gimmick::DeleteDrive(const std::string& drive)
00463   {
00464         for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
00465                                                it!= mTreeHandlerMap.end(); 
00466                                                ++it)
00467            {
00468                    mImageAdder.SetTreeHandler(it->second);
00469                    mImageAdder.DeleteDriveFromMainDB(drive);
00470            }
00471         mImageAdder.SetSynchronizer(mSynchronizer);
00472         mImageAdder.DeleteDriveFromOtherDB(drive);
00473   }
00474 
00475   //========================================================================
00476   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
00477   {
00478         TreeHandler * handler=GetTreeHandler(d);
00479         mImageAdder.SetCurrentDatabase(d);
00480         mImageAdder.SetTreeHandler(handler);
00481         mImageAdder.EditField(node,name,key,val);
00482   }
00483   //========================================================================
00484 
00486   // add DB from Settings file                                          //
00487   // @param : -                                                         //
00488   // return : -                                                         //
00490   void Gimmick::addDBSettings()
00491   {
00492 
00493          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
00494          
00495          // split to find all paths
00496          std::vector<std::string> paths;
00497          std::string separator = ";";
00498          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
00499          //find first separator
00500          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
00501          while(std::string::npos != pos || std::string::npos != last_pos)
00502          {
00503                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
00504                 last_pos = pathSettings.find_first_not_of(separator, pos);
00505                 pos = pathSettings.find_first_of(separator, last_pos);
00506          }
00507 
00508          std::vector<std::string>::iterator it_path = paths.begin();
00509          for(; it_path != paths.end(); ++it_path)
00510          {
00511                  pos = it_path->find_last_of("\\");
00512                  last_pos = it_path->find_last_of(".");
00513                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
00514                  addDB(name, it_path->c_str());
00515          }
00516   }     
00517 
00518 
00520 // Fill attributes structure with attributes present in database (inside vector
00521 // and not present (outside)
00523 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
00524 {
00525         //test if a tag is present in Database descriptor
00526         TreeHandler * handler=GetTreeHandler(infos.db);
00527         mImageAdder.SetTreeHandler(handler);
00528         std::vector<std::string>::const_iterator it = i_attr.begin();
00529         for (;it != i_attr.end(); it++)
00530         {
00531                 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
00532                 {
00533                         infos.inside.push_back((*it));
00534                 }
00535                 else
00536                 {
00537                                 infos.outside.push_back((*it)); // Need to scan again the files
00538                 }
00539         }
00540 }
00541 
00542 const std::string Gimmick::getSummary()
00543 {
00544       const AddProgress& p = GetAddProgress();
00545     std::stringstream mess;
00546     mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs()  << "\n";
00547     mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
00548     mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
00549     mess << "Files\tadded  \t: " << p.GetNumberAddedFiles()   << "\n\n";
00550     return mess.str();
00551 }
00552 
00553 }