Back to index

salome-kernel  6.5.0
SALOMEDS_Tool.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00004 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00005 //
00006 // This library is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 2.1 of the License.
00010 //
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 // Lesser General Public License for more details.
00015 //
00016 // You should have received a copy of the GNU Lesser General Public
00017 // License along with this library; if not, write to the Free Software
00018 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00019 //
00020 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00021 //
00022 
00023 //  File      : SALOMEDS_Tool.cxx
00024 //  Created   : Mon Oct 21 16:24:34 2002
00025 //  Author    : Sergey RUIN
00026 //  Project   : SALOME
00027 //  Module    : SALOMEDS
00028 //
00029 #include "SALOMEDS_Tool.hxx"
00030 
00031 #include "utilities.h"
00032 #include "Basics_DirUtils.hxx"
00033 
00034 #ifndef WIN32
00035 #include <sys/time.h>
00036 #include <sys/stat.h>
00037 #include <sys/types.h>
00038 #include <pwd.h> 
00039 #include <unistd.h>
00040 #else
00041 #include <time.h>
00042 #include <lmcons.h>
00043 #endif
00044 
00045 #include <iostream> 
00046 #include <fstream>
00047 #include <stdlib.h>
00048 
00049 #include <SALOMEconfig.h>
00050 #include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
00051 
00052 bool Exists(const std::string thePath) 
00053 {
00054 #ifdef WIN32 
00055   if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
00056     if (  GetLastError () == ERROR_FILE_NOT_FOUND  ) {
00057       return false;
00058     }
00059   }
00060 #else 
00061   int status = access ( thePath.c_str() , F_OK ); 
00062   if (status != 0) return false;
00063 #endif
00064   return true;
00065 }
00066 
00067 
00068 //============================================================================
00069 // function : GetTempDir
00070 // purpose  : Return a temp directory to store created files like "/tmp/sub_dir/" 
00071 //============================================================================ 
00072 std::string SALOMEDS_Tool::GetTmpDir()
00073 {
00074   return Kernel_Utils::GetTmpDirByEnv("SALOME_TMP_DIR");
00075   //Find a temporary directory to store a file
00076 
00077   /*string aTmpDir = "";
00078 
00079   char *Tmp_dir = getenv("SALOME_TMP_DIR");
00080   if(Tmp_dir != NULL) {
00081     aTmpDir = string(Tmp_dir);
00082 #ifdef WIN32
00083     if(aTmpDir[aTmpDir.size()-1] != '\\') aTmpDir+='\\';
00084 #else
00085     if(aTmpDir[aTmpDir.size()-1] != '/') aTmpDir+='/';
00086 #endif      
00087   }
00088   else {
00089 #ifdef WIN32
00090     aTmpDir = string("C:\\");
00091 #else
00092     aTmpDir = string("/tmp/");
00093 #endif
00094   }
00095 
00096   srand((unsigned int)time(NULL));
00097   int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
00098   char buffer[127];
00099   sprintf(buffer, "%d", aRND);
00100   string aSubDir(buffer);
00101   if(aSubDir.size() <= 1) aSubDir = string("123409876");
00102 
00103   aTmpDir += aSubDir; //Get RND sub directory
00104 
00105   string aDir = aTmpDir;
00106 
00107   if(Exists(aDir)) {
00108     for(aRND = 0; Exists(aDir); aRND++) {
00109       sprintf(buffer, "%d", aRND);
00110       aDir = aTmpDir+buffer;  //Build a unique directory name
00111     }
00112   }
00113 
00114 #ifdef WIN32
00115   if(aDir[aDir.size()-1] != '\\') aDir+='\\';
00116 #else
00117   if(aDir[aTmpDir.size()-1] != '/') aDir+='/';
00118 #endif
00119 
00120 
00121 #ifdef WIN32
00122   CreateDirectory(aDir.c_str(), NULL);
00123 #else
00124   mkdir(aDir.c_str(), 0x1ff); 
00125 #endif
00126 
00127   return aDir;*/
00128 }
00129 
00130 //============================================================================
00131 // function : RemoveTemporaryFiles
00132 // purpose  : Removes files listed in theFileList
00133 //============================================================================
00134 void SALOMEDS_Tool::RemoveTemporaryFiles(const std::string& theDirectory, 
00135                                          const SALOMEDS::ListOfFileNames& theFiles,
00136                                          const bool IsDirDeleted)
00137 {
00138   std::string aDirName = theDirectory;
00139 
00140   int i, aLength = theFiles.length();
00141   for(i=1; i<=aLength; i++) {
00142     std::string aFile(aDirName);
00143     aFile += theFiles[i-1];
00144     if(!Exists(aFile)) continue;
00145 
00146 #ifdef WIN32
00147     DeleteFile(aFile.c_str());
00148 #else 
00149     unlink(aFile.c_str());
00150 #endif
00151   }
00152 
00153   if(IsDirDeleted) {
00154     if(Exists(aDirName)) {
00155 #ifdef WIN32
00156       RemoveDirectory(aDirName.c_str());
00157 #else
00158       rmdir(aDirName.c_str());
00159 #endif
00160     }
00161   }
00162 
00163 }
00164 
00165 //============================================================================
00166 // function : PutFilesToStream
00167 // purpose  : converts the files from a list 'theFiles' to the stream
00168 //============================================================================
00169 namespace
00170 {
00171   SALOMEDS::TMPFile* 
00172   PutFilesToStream(const std::string& theFromDirectory,
00173                    const SALOMEDS::ListOfFileNames& theFiles,
00174                    const SALOMEDS::ListOfFileNames& theFileNames,
00175                    const int theNamesOnly)
00176   {
00177     int i, aLength = theFiles.length();
00178     if(aLength == 0)
00179       return (new SALOMEDS::TMPFile);
00180     
00181     //Get a temporary directory for saved a file
00182     std::string aTmpDir = theFromDirectory;
00183     
00184     long aBufferSize = 0;
00185     long aCurrentPos;
00186     
00187     int aNbFiles = 0;
00188     int* aFileNameSize= new int[aLength];
00189     long* aFileSize= new long[aLength];
00190     
00191     //Determine the required size of the buffer
00192     
00193     for(i=0; i<aLength; i++) {
00194       
00195       //Check if the file exists
00196       
00197       if (!theNamesOnly) { // mpv 15.01.2003: if only file names must be stroed, then size of files is zero
00198         std::string aFullPath = aTmpDir + const_cast<char*>(theFiles[i].in());   
00199         if(!Exists(aFullPath)) continue;
00200 #ifdef WIN32
00201         std::ifstream aFile(aFullPath.c_str(), std::ios::binary);
00202 #else
00203         std::ifstream aFile(aFullPath.c_str());
00204 #endif
00205         aFile.seekg(0, std::ios::end);
00206         aFileSize[i] = aFile.tellg();
00207         aBufferSize += aFileSize[i];              //Add a space to store the file
00208       }
00209       aFileNameSize[i] = strlen(theFileNames[i])+1;
00210       aBufferSize += aFileNameSize[i];          //Add a space to store the file name
00211       aBufferSize += (theNamesOnly)?4:12;       //Add 4 bytes: a length of the file name,
00212       //    8 bytes: length of the file itself
00213       aNbFiles++;
00214     } 
00215     
00216     if ( aNbFiles == 0 ) return (new SALOMEDS::TMPFile);
00217     aBufferSize += 4;      //4 bytes for a number of the files that will be written to the stream;
00218     unsigned char* aBuffer = new unsigned char[aBufferSize];  
00219     if(aBuffer == NULL)
00220       return (new SALOMEDS::TMPFile);
00221     
00222     //Initialize 4 bytes of the buffer by 0
00223     memset(aBuffer, 0, 4); 
00224     //Copy the number of files that will be written to the stream
00225     memcpy(aBuffer, &aNbFiles, ((sizeof(int) > 4) ? 4 : sizeof(int))); 
00226     
00227     
00228     aCurrentPos = 4;
00229     
00230     for(i=0; i<aLength; i++) {
00231       std::ifstream *aFile;
00232       if (!theNamesOnly) { // mpv 15.01.2003: we don't open any file if theNamesOnly = true
00233         std::string aFullPath = aTmpDir + const_cast<char*>(theFiles[i].in());
00234         if(!Exists(aFullPath)) continue;
00235 #ifdef WIN32
00236         aFile = new std::ifstream(aFullPath.c_str(), std::ios::binary);
00237 #else
00238         aFile = new std::ifstream(aFullPath.c_str());
00239 #endif  
00240       }
00241       //Initialize 4 bytes of the buffer by 0
00242       memset((aBuffer + aCurrentPos), 0, 4); 
00243       //Copy the length of the file name to the buffer
00244       memcpy((aBuffer + aCurrentPos), (aFileNameSize + i), ((sizeof(int) > 4) ? 4 : sizeof(int))); 
00245       aCurrentPos += 4;
00246       
00247       //Copy the file name to the buffer
00248       memcpy((aBuffer + aCurrentPos), theFileNames[i], aFileNameSize[i]);
00249       aCurrentPos += aFileNameSize[i];
00250       
00251       if (!theNamesOnly) { // mpv 15.01.2003: we don't copy file content to the buffer if !theNamesOnly
00252         //Initialize 8 bytes of the buffer by 0
00253         memset((aBuffer + aCurrentPos), 0, 8); 
00254         //Copy the length of the file to the buffer
00255         memcpy((aBuffer + aCurrentPos), (aFileSize + i), ((sizeof(long) > 8) ? 8 : sizeof(long)));
00256         aCurrentPos += 8;
00257         
00258         aFile->seekg(0, std::ios::beg);
00259         aFile->read((char *)(aBuffer + aCurrentPos), aFileSize[i]);
00260         aFile->close();
00261         delete(aFile);
00262         aCurrentPos += aFileSize[i];
00263       }
00264     }
00265     
00266     delete[] aFileNameSize;
00267     delete[] aFileSize;
00268     
00269     
00270     CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
00271     
00272     return (new SALOMEDS::TMPFile(aBufferSize, aBufferSize, anOctetBuf, 1));
00273   }
00274   
00275 }
00276 
00277 
00278 SALOMEDS::TMPFile* 
00279 SALOMEDS_Tool::PutFilesToStream(const std::string& theFromDirectory,
00280                                 const SALOMEDS::ListOfFileNames& theFiles,
00281                                 const int theNamesOnly)
00282 {
00283   SALOMEDS::ListOfFileNames aFileNames(theFiles);
00284   return ::PutFilesToStream(theFromDirectory,theFiles,aFileNames,theNamesOnly);
00285 }
00286 
00287 
00288 SALOMEDS::TMPFile* 
00289 SALOMEDS_Tool::PutFilesToStream(const SALOMEDS::ListOfFileNames& theFiles,
00290                                 const SALOMEDS::ListOfFileNames& theFileNames)
00291 {
00292   return ::PutFilesToStream("",theFiles,theFileNames,0);
00293 }
00294 
00295 //============================================================================
00296 // function : PutStreamToFile
00297 // purpose  : converts the stream "theStream" to the files
00298 //============================================================================
00299 SALOMEDS::ListOfFileNames_var 
00300 SALOMEDS_Tool::PutStreamToFiles(const SALOMEDS::TMPFile& theStream,
00301                                 const std::string& theToDirectory,
00302                                 const int theNamesOnly)
00303 {
00304   SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
00305 
00306   if(theStream.length() == 0)
00307     return aFiles;
00308 
00309   //Get a temporary directory for saving a file
00310   std::string aTmpDir = theToDirectory;
00311 
00312   unsigned char *aBuffer = (unsigned char*)theStream.NP_data();
00313 
00314   if(aBuffer == NULL)
00315     return aFiles;
00316 
00317   long aFileSize, aCurrentPos = 4;
00318   int i, aFileNameSize, aNbFiles = 0;
00319 
00320   //Copy the number of files in the stream
00321   memcpy(&aNbFiles, aBuffer, sizeof(int)); 
00322 
00323   aFiles->length(aNbFiles);
00324 
00325   for(i=0; i<aNbFiles; i++) {
00326 
00327     //Put a length of the file name to aFileNameSize
00328     memcpy(&aFileNameSize, (aBuffer + aCurrentPos), ((sizeof(int) > 4) ? 4 : sizeof(int))); 
00329     aCurrentPos += 4;
00330 
00331     char *aFileName = new char[aFileNameSize];
00332     //Put a file name to aFileName
00333     memcpy(aFileName, (aBuffer + aCurrentPos), aFileNameSize); 
00334 #ifdef WIN32
00335     for (int i = 0; i < strlen(aFileName); i++)
00336     {
00337       if (aFileName[i] == ':')
00338        aFileName[i] = '_';
00339     }
00340 #endif
00341     aCurrentPos += aFileNameSize;
00342  
00343     //Put a length of the file to aFileSize
00344     if (!theNamesOnly) {
00345       memcpy(&aFileSize, (aBuffer + aCurrentPos), ((sizeof(long) > 8) ? 8 : sizeof(long)));
00346       aCurrentPos += 8;    
00347       
00348       std::string aFullPath = aTmpDir + aFileName;
00349 #ifdef WIN32
00350       std::ofstream aFile(aFullPath.c_str(), std::ios::binary);
00351 #else
00352       std::ofstream aFile(aFullPath.c_str());
00353 #endif
00354       aFile.write((char *)(aBuffer+aCurrentPos), aFileSize); 
00355       aFile.close();  
00356       aCurrentPos += aFileSize;
00357     }
00358     aFiles[i] = CORBA::string_dup(aFileName);
00359     delete[] aFileName;
00360   }
00361 
00362   return aFiles;
00363 }
00364 
00365 //============================================================================
00366 // function : GetNameFromPath
00367 // purpose  : Returns the name by the path
00368 //============================================================================
00369 std::string SALOMEDS_Tool::GetNameFromPath(const std::string& thePath) {
00370   if (thePath.empty()) return "";
00371   std::string aPath = thePath;
00372   bool isFound = false;
00373   int pos = aPath.rfind('/');
00374   if(pos > 0) {
00375     aPath = aPath.substr(pos+1, aPath.size());
00376     isFound = true;
00377   }    
00378   if(!isFound) {
00379     pos = aPath.rfind('\\'); 
00380     if(pos > 0) {
00381       aPath = aPath.substr(pos+1, aPath.size()); 
00382       isFound = true;
00383     }  
00384   }  
00385   if(!isFound) {  
00386     pos = aPath.rfind('|');
00387     if(pos > 0) aPath =  aPath.substr(pos+1, aPath.size()); 
00388   }
00389 
00390   pos = aPath.rfind('.'); 
00391   if(pos > 0)  aPath = aPath.substr(0, pos); //Remove extension
00392     
00393   return aPath;
00394 }
00395 
00396 //============================================================================
00397 // function : GetDirFromPath
00398 // purpose  : Returns the dir by the path
00399 //============================================================================
00400 std::string SALOMEDS_Tool::GetDirFromPath(const std::string& thePath) {
00401   if (thePath.empty()) return "";
00402 
00403   int pos = thePath.rfind('/');
00404   std::string path;
00405   if(pos > 0) {
00406     path = thePath.substr(0, pos+1);
00407   }
00408   if(path.empty()) {
00409     pos = thePath.rfind('\\');
00410     if(pos > 0) path = thePath.substr(0, pos+1); 
00411   }
00412   if(path.empty()) {
00413     pos = thePath.rfind('|');
00414     if(pos > 0) path = thePath.substr(0, pos+1); 
00415   }
00416   if(path.empty()) {
00417     path = thePath+"/";
00418   }
00419   
00420 #ifdef WIN32  //Check if the only disk letter is given as path
00421   if(path.size() == 2 && path[1] == ':') path +='\\';
00422 #endif
00423 
00424   for(int i = 0, len = path.size(); i<len; i++) 
00425     if(path[i] == '|') path[i] = '/';
00426   return path;
00427 }
00428 
00429 //=======================================================================
00430 // name    : GetFlag
00431 // Purpose : Retrieve specified flaf from "AttributeFlags" attribute
00432 //=======================================================================
00433 bool SALOMEDS_Tool::GetFlag( const int             theFlag,
00434                              SALOMEDS::Study_var   theStudy,
00435                              SALOMEDS::SObject_var theObj )
00436 {
00437   SALOMEDS::GenericAttribute_var anAttr;
00438   if ( !theObj->_is_nil() && theObj->FindAttribute( anAttr, "AttributeFlags" ) )
00439   {
00440     SALOMEDS::AttributeFlags_var aFlags = SALOMEDS::AttributeFlags::_narrow( anAttr );
00441     return aFlags->Get( theFlag );
00442   }
00443 
00444   return false;
00445 }
00446 
00447 //=======================================================================
00448 // name    : SetFlag
00449 // Purpose : Set/Unset specified flaf from "AttributeFlags" attribute
00450 //=======================================================================
00451 bool SALOMEDS_Tool::SetFlag( const int           theFlag,
00452                              SALOMEDS::Study_var theStudy,
00453                              const std::string&  theEntry,
00454                              const bool          theValue )
00455 {
00456   SALOMEDS::SObject_var anObj = theStudy->FindObjectID(theEntry.c_str());
00457 
00458   if ( !anObj->_is_nil() )
00459   {
00460     SALOMEDS::GenericAttribute_var aGAttr;
00461     if ( anObj->FindAttribute( aGAttr, "AttributeFlags" ) )
00462     {
00463       SALOMEDS::AttributeFlags_var anAttr = SALOMEDS::AttributeFlags::_narrow( aGAttr );
00464       anAttr->Set( theFlag, theValue );
00465     }
00466     else if ( theValue )
00467     {
00468       SALOMEDS::StudyBuilder_var aBuilder = theStudy->NewBuilder();
00469       SALOMEDS::AttributeFlags_var anAttr = SALOMEDS::AttributeFlags::_narrow(
00470         aBuilder->FindOrCreateAttribute( anObj, "AttributeFlags" ) );
00471       anAttr->Set( theFlag, theValue );
00472     }
00473     return true;
00474   }
00475 
00476   return false;
00477 }
00478 
00479 //=======================================================================
00480 // name    : getAllChildren
00481 // Purpose : Get all children of object.
00482 //           If theObj is null all objects of study are returned
00483 //=======================================================================
00484 void SALOMEDS_Tool::GetAllChildren( SALOMEDS::Study_var               theStudy,
00485                                     SALOMEDS::SObject_var             theObj,
00486                                     std::list<SALOMEDS::SObject_var>& theList )
00487 {
00488   if ( theObj->_is_nil() )
00489   {
00490     SALOMEDS::SComponentIterator_var anIter = theStudy->NewComponentIterator();
00491     for ( ; anIter->More(); anIter->Next() )
00492     {
00493       SALOMEDS::SObject_var anObj = SALOMEDS::SObject::_narrow( anIter->Value() );
00494       if ( !anObj->_is_nil() )
00495       {
00496         theList.push_back( anObj );
00497         GetAllChildren( theStudy, anObj, theList );
00498       }
00499     }
00500   }
00501   else
00502   {
00503     SALOMEDS::ChildIterator_var anIter = theStudy->NewChildIterator( theObj );
00504     for ( ; anIter->More(); anIter->Next() )
00505     {
00506       SALOMEDS::SObject_var anObj = anIter->Value();
00507       SALOMEDS::SObject_var aRef;
00508       if ( !anObj->ReferencedObject( aRef ) )
00509       {
00510         theList.push_back( anObj );
00511         GetAllChildren( theStudy, anObj, theList );
00512       }
00513     }
00514   }
00515 }
00516 
00517 
00518