creaImageIO_lib
creaImageIOGimmick.cpp
Go to the documentation of this file.
1 /*
2 # ---------------------------------------------------------------------
3 #
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
5 # pour la Santé)
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
9 #
10 # This software is governed by the CeCILL-B license under French law and
11 # abiding by the rules of distribution of free software. You can use,
12 # modify and/ or redistribute the software under the terms of the CeCILL-B
13 # license as circulated by CEA, CNRS and INRIA at the following URL
14 # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
15 # or in the file LICENSE.txt.
16 #
17 # As a counterpart to the access to the source code and rights to copy,
18 # modify and redistribute granted by the license, users are provided only
19 # with a limited warranty and the software's author, the holder of the
20 # economic rights, and the successive licensors have only limited
21 # liability.
22 #
23 # The fact that you are presently reading this means that you have had
24 # knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------
26 */
27 
28 #include <creaImageIOGimmick.h>
29 
30 #include <boost/filesystem.hpp>
31 #include <boost/algorithm/string.hpp>
32 
33 //#include "io.h"
34 #ifndef PATH_MAX // If not defined yet : do it
35 # define PATH_MAX 2048
36 #endif
37 #include <creaImageIOGimmick.h>
38 
39 #if defined(_WIN32)
40 #pragma warning(disable: 4996)
41 #endif
42 
43 #ifdef _DEBUG
44 #define new DEBUG_NEW
45 #endif
46 
47 
48 namespace creaImageIO
49 {
50  //==============================================================
52  : mImageAdder(0)
53  {
55  mSettings=0;
56  mSynchronizer=0;
57  mLocalDescpName = "localdatabase_Descriptor.dscp";
58  mLocalDBName = "Local database";
59  }
60  //==============================================================
61 
62 
63  //==============================================================
65  {
66 
67  if(mSettings!=0)
68  {
70  delete mSettings;
71  }
72  if(mSynchronizer!=0)
73  {
74  delete mSynchronizer;
75  }
76  }
77  //==============================================================
78 
79  //==============================================================
80  void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
81  {
82  mLocalDescpName = i_namedescp;
83  mLocalDBName = i_namedb;
84  Initialize();
85  }
86 
87  //==============================================================
89  {
90  std::string i_nameDB = mLocalDBName;
91  // Create the UserSettings dir if does not exist
93  // Sets the current directory to the home dir
95  mSynchronizer= new Synchronizer(GetUserSettingsDirectory()+"share/creaImageIO/");
96 
98 
99  std::string dbpath = GetLocalDatabasePath();
100 
101  // Create or open local database
102  std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
103 
104  boost::algorithm::replace_all( dpath,
107  mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
108  // Add it to the TreeHandlerMap
109  mTreeHandlerMap[i_nameDB] = mLocalDatabase;
110 
111  //Add additional DB from user Settings
112  addDBSettings();
113  }
114 
116  // add DB to TreeHandler Map //
117  // @param i_name : DB name //
118  // @param i_location : DB location //
119  // return : - //
121  void Gimmick::addDB(const std::string &i_name,
122  const std::string &i_location)
123  {
124  if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
125  {
126  mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
127  mTreeHandlerMap[i_name]->Open(true);
128  mSettings->addDB(i_location);
129  }
130  }
131 
133  // create a DB from a attributes descriptor file for medical images //
134  // @param i_name : DB name //
135  // @param i_locDesc : location of descriptor file //
136  // @param i_locDB : location of DB //
137  // return : the SQLiteTreeHandler object on DB //
139  SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
140  const std::string &i_locDesc,
141  const std::string &i_locDB)
142  {
143  SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
144  // Create or open local database
145  if (! boost::filesystem::exists(i_locDB) )
146  {
147  std::string mess = "Local database '";
148  mess += i_locDB;
149  mess += "' does not exist : creating it";
150  GimmickMessage(1,mess<<std::endl);
151 
152  // CREATING DB STRUCTURE
153  sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
154  if ( ! sqlTreeH->Create(true) )
155  {
156  GimmickError("ERROR CREATING '"<<i_locDB<<"'");
157  }
158  sqlTreeH->SetAttribute(0,"Name",i_name);
159  }
160  else
161  {
163 
164  GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
165  if ( !sqlTreeH->Open(true) )
166  {
167  GimmickError("ERROR OPENING '"<<i_locDB<<"'");
168  }
169  }
170  return sqlTreeH;
171  }
172 
173  //==============================================================
175  {
176  if(mTreeHandlerMap.size() >0)
177  {
178  // delete SQLiteTreeHandler Object
179  for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
180  it!= mTreeHandlerMap.end();
181  ++it)
182  {
183  delete it->second;
184  }
185  }
186  }
187  //==============================================================
188 
189  //================================================================
190  // file separator
191 #if defined(_WIN32)
192 #define VALID_FILE_SEPARATOR "\\"
193 #define INVALID_FILE_SEPARATOR "/"
194 #else
195 #define INVALID_FILE_SEPARATOR "\\"
196 #define VALID_FILE_SEPARATOR "/"
197 #endif
198  //================================================================
199 
200  //================================================================
201  const std::string& Gimmick::GetHomeDirectory()
202  {
203  if (mHomeDirectory.size()==0)
204  {
205 #if defined(__GNUC__)
206  mHomeDirectory = getenv("HOME");
207 #elif defined(_WIN32)
208  mHomeDirectory = getenv("USERPROFILE");
209 #endif
210  }
211  return mHomeDirectory;
212  }
213  //================================================================
215  {
216  if (mUserSettingsDirectory.size()==0)
217  {
219  mUserSettingsDirectory += "/.creaImageIO/";
220  boost::algorithm::replace_all( mUserSettingsDirectory,
223  }
224  return mUserSettingsDirectory;
225  }
226  //================================================================
227 
228 
229  //================================================================
230  const std::string& Gimmick::GetLocalDatabasePath()
231  {
232  if (mLocalDatabasePath.size()==0)
233  {
235  mLocalDatabasePath += "share/creaImageIO/";
237  mLocalDatabasePath +=".sqlite3";
238  boost::algorithm::replace_all( mLocalDatabasePath,
241  }
242  return mLocalDatabasePath;
243  }
244 
245  //========================================================================
246 
247  //========================================================================
249  {
250 
251  // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
252  // boost::algorithm::replace_all( st,
253  // INVALID_FILE_SEPARATOR ,
254  // VALID_FILE_SEPARATOR);
255  //const boost::filesystem::path mpath(st);
256 //C:\Documents and Settings\cervenansky\.gimmick");
257  //if ( !boost::filesystem::exists( path ) ) return ;
258  // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
259  // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
260  // {
262  // if ( boost::filesystem::is_directory(itr->status()) )
263  // return;
264  // }
265 
266  //JCP settings dir 02/10/2009
267  const std::string settingsdirectory = GetUserSettingsDirectory();
268  //boost::algorithm::replace_all( mUserSettingsDirectory,
269  // INVALID_FILE_SEPARATOR ,
270  // VALID_FILE_SEPARATOR);
271 ;//("E:\frederic");
272  //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
273  bool isdir = false;
274  isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
275  if (! isdir )
276  {
277  GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
278  << "does not exist : creating it"<<std::endl);
279 
280  if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
281  {
282  GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
283  }
284  }
285 
286  std::string setDir=GetUserSettingsDirectory();
287  boost::algorithm::replace_all( setDir,
290  setDir+="share/";
291  boost::filesystem::create_directory( setDir );
292  setDir+="creaImageIO/";
293  boost::filesystem::create_directory( setDir );
294  setDir+=mLocalDescpName;
295 
296  if(!boost::filesystem::is_regular(setDir))
297  {
298  char name[PATH_MAX];
299  crea::System::GetAppPath(name,PATH_MAX);
300  std::cout<<name<<std::endl;
301 
302  std::string path=name;
303  path=path.substr(0,path.size()-1);
304  path=path.substr(0,path.find_last_of("/"));
305  //Creating directories
306 
307 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
308 
309 #if defined(_WIN32)
310  path+="/bin/share/creaImageIO/";
311 #endif
312 
313 #if defined (LINUX)
314  path+="/../share/creaImageIO/";
315 #endif
316 #if defined(__APPLE__)
317  path+="/../../../../share/creaImageIO/";
318 #endif
319 
320 
321 path+= mLocalDescpName;
322 
323  std::cout <<"From: " << path <<std::endl;
324  std::cout <<"To: " << setDir <<std::endl;
325  boost::algorithm::replace_all( path,
328  boost::filesystem::copy_file(path,setDir);
329  }
330 
331  }
332  //========================================================================
333 
334 
335  //========================================================================
338  {
340  }
341  //========================================================================
342 
343  //========================================================================
346  {
348  }
349  //========================================================================
350 
351  //========================================================================
353  TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
354  {
355  TreeHandlerMapType::const_iterator i;
356  i = GetTreeHandlerMap().find(name);
357  if ( i == GetTreeHandlerMap().end() )
358  {
359  GimmickError("TreeHandler '"<<name<<"' does not exist");
360  }
361  return i->second;
362  }
363 
364  //========================================================================
366  void Gimmick::AddFiles(const std::string& d,
367  const std::vector<std::string>& filenames)
368  {
369  GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
370 
374  mImageAdder.AddFiles(filenames);
375  }
376  //========================================================================
377 
378  //========================================================================
380  void Gimmick::AddDir(const std::string& d, const std::string& f,
381  bool recurse)
382  {
383  GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
384  <<recurse<<std::endl);
385 
386  TreeHandler * handler=GetTreeHandler(d);
388  mImageAdder.SetTreeHandler(handler);
390  mImageAdder.AddDirectory(f,recurse);
391  }
392 
393  //========================================================================
394 
395  //========================================================================
396  void Gimmick::RemoveFile(const std::string& d,
397  tree::Node* node)
398  {
401  mImageAdder.RemoveFile(node);
402  }
403  //========================================================================
404 
405  //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
406  //========================================================================
407 
408  void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
409  {
410  TreeHandler * handler=GetTreeHandler(d);
412  mImageAdder.SetTreeHandler(handler);
415  }
416 
417  //========================================================================
418 
419  std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
420  {
421  TreeHandler * handler=GetTreeHandler(d);
423  mImageAdder.SetTreeHandler(handler);
425  return mImageAdder.Synchronize(repair, checkAttributes);
426  }
427 
428  //========================================================================
430  void Gimmick::Print(const std::string& d)
431  {
432  GetTreeHandler(d)->GetTree().Print();
433  }
434  //========================================================================
435 
436  void Gimmick::GetSetting(const std::string& name, std::string& value)
437  {
438  value = mSettings->getValue(name);
439  }
440  //========================================================================
441 
442  //========================================================================
443 
444  void Gimmick::GetAttributes(const std::string& d,
445  const std::string& filename,
446  const std::vector<std::string>& params,
447  std::vector<std::string>& results)
448  {
449  TreeHandler * handler=GetTreeHandler(d);
451  mImageAdder.SetTreeHandler(handler);
453  mImageAdder.GetAttributes(params, filename, results);
454  }
455  //========================================================================
456 
457  //========================================================================
458  // get attributes values from database for a given file from database
459  //========================================================================
460  void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
461  {
462  if (i_attr.inside.size() > 0)
463  {
464  std::map<std::string, std::string> map_attr;
465  TreeHandler * handler=GetTreeHandler(i_attr.db);
466  handler->getAllAttributes(filename, map_attr);
467  if(i_attr.inside.front() == "ALL") // we take all values
468  {
469  std::map<std::string, std::string>::iterator it = map_attr.begin();
470  for(; it != map_attr.end(); it++)
471  i_res[it->first] = it->second;
472  }
473  else
474  {
475  std::vector<std::string>::iterator it = i_attr.inside.begin();
476  for(; it != i_attr.inside.end(); it++)
477  i_res[(*it)] = map_attr[(*it)];
478  }
479  }
480  }
481 
482 
483  //========================================================================
484 
485  void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
486  {
487  mSettings->updateSetting(name,value);
489  }
490  //========================================================================
491 
492  void Gimmick::DeleteDrive(const std::string& drive)
493  {
494  for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
495  it!= mTreeHandlerMap.end();
496  ++it)
497  {
498  mImageAdder.SetTreeHandler(it->second);
500  }
503  }
504 
505  //========================================================================
506  void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
507  {
508  TreeHandler * handler=GetTreeHandler(d);
510  mImageAdder.SetTreeHandler(handler);
511  mImageAdder.EditField(node,name,key,val);
512  }
513  //========================================================================
514 
516  // add DB from Settings file //
517  // @param : - //
518  // return : - //
521  {
522 
523  std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
524 
525  // split to find all paths
526  std::vector<std::string> paths;
527  std::string separator = ";";
528  std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
529  //find first separator
530  std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
531  while(std::string::npos != pos || std::string::npos != last_pos)
532  {
533  paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
534  last_pos = pathSettings.find_first_not_of(separator, pos);
535  pos = pathSettings.find_first_of(separator, last_pos);
536  }
537 
538  std::vector<std::string>::iterator it_path = paths.begin();
539  for(; it_path != paths.end(); ++it_path)
540  {
541  pos = it_path->find_last_of("\\");
542  last_pos = it_path->find_last_of(".");
543  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
544  addDB(name, it_path->c_str());
545  }
546  }
547 
548 
550 // Fill attributes structure with attributes present in database (inside vector
551 // and not present (outside)
553 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
554 {
555  //test if a tag is present in Database descriptor
556  TreeHandler * handler=GetTreeHandler(infos.db);
557  mImageAdder.SetTreeHandler(handler);
558  std::vector<std::string>::const_iterator it = i_attr.begin();
559  for (;it != i_attr.end(); it++)
560  {
561  if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
562  {
563  infos.inside.push_back((*it));
564  }
565  else
566  {
567  infos.outside.push_back((*it)); // Need to scan again the files
568  }
569  }
570 }
571 
572 const std::string Gimmick::getSummary()
573 {
574  const AddProgress& p = GetAddProgress();
575  std::stringstream mess;
576  mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs() << "\n";
577  mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
578  mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
579  mess << "Files\tadded \t: " << p.GetNumberAddedFiles() << "\n\n";
580  return mess.str();
581 }
582 
583 }