Salome HOME
Update copyrights
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_Tool.cxx
1 // Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  File      : SALOMEDSImpl_Tool.cxx
24 //  Created   : Mon Oct 21 16:24:34 2002
25 //  Author    : Sergey RUIN
26 //  Project   : SALOME
27 //  Module    : SALOMEDSImpl
28 //
29 #include <stdio.h>
30 #include <iostream> 
31 #include <fstream>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <iterator>
35 #include <sstream>
36
37 #include "SALOMEDSImpl_Tool.hxx"
38
39 #ifndef WIN32
40 #include <sys/time.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <pwd.h> 
44 #include <unistd.h>
45 #else
46 #include <time.h>
47 #include <lmcons.h>
48 //#include <winbase.h>
49 #include <windows.h>
50 #endif
51
52
53 bool SALOMEDS_Exists(const std::string thePath)
54 {
55 #ifdef WIN32 
56   if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
57     if (  GetLastError () == ERROR_FILE_NOT_FOUND  ) {
58       return false;
59     }
60   }
61 #else 
62   int status = access ( thePath.c_str() , F_OK ); 
63   if (status != 0) return false;
64 #endif
65   return true;
66 }
67
68
69
70
71 //============================================================================
72 // function : GetTempDir
73 // purpose  : Return a temp directory to store created files like "/tmp/sub_dir/"
74 //============================================================================
75 std::string SALOMEDSImpl_Tool::GetTmpDir()
76 {
77   //Find a temporary directory to store a file
78
79   std::string aTmpDir;
80
81   char *Tmp_dir = getenv("SALOME_TMP_DIR");
82   if ( Tmp_dir != NULL && SALOMEDS_Exists( Tmp_dir ))
83   {
84     aTmpDir = Tmp_dir;
85 #ifdef WIN32
86     if ( aTmpDir.back() != '\\') aTmpDir += '\\';
87 #else
88     if ( aTmpDir.back() != '/') aTmpDir += '/';
89 #endif
90   }
91   else
92   {
93 #ifdef WIN32
94     aTmpDir = "C:\\";
95 #else
96     aTmpDir = "/tmp/";
97 #endif
98   }
99
100   srand( (unsigned int)time( NULL ));
101   int aRND = 999 + (int) (100000.0*rand() / (RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
102   char buffer[127];
103   sprintf( buffer, "%d", aRND );
104   std::string aSubDir( buffer );
105   if ( aSubDir.size() <= 1 ) aSubDir = "123409876";
106
107   aTmpDir += aSubDir; //Get RND sub directory
108
109   std::string aDir = aTmpDir;
110
111   for ( aRND = 0; SALOMEDS_Exists( aDir ); aRND++ )
112   {
113     sprintf(buffer, "%d", aRND);
114     aDir = aTmpDir + buffer;  //Build a unique directory name
115   }
116
117 #ifdef WIN32
118   if ( aDir.back() != '\\') aDir += '\\';
119 #else
120   if ( aDir.back() != '/' ) aDir += '/';
121 #endif
122
123
124 #ifdef WIN32
125   CreateDirectory( aDir.c_str(), NULL );
126 #else
127   mkdir( aDir.c_str(), 0x1ff );
128 #endif
129
130   return aDir;
131 }
132
133 //============================================================================
134 // function : RemoveTemporaryFiles
135 // purpose  : Removes files listed in theFileList
136 //============================================================================
137 void SALOMEDSImpl_Tool::RemoveTemporaryFiles(const std::string& theDirectory,
138                                              const std::vector<std::string>& theFiles,
139                                              const bool IsDirDeleted)
140 {
141   std::string aDirName = theDirectory;
142
143   int i, aLength = theFiles.size();
144   for(i=1; i<=aLength; i++) {
145     std::string aFile(aDirName);
146     aFile += theFiles[i-1];
147     if(!SALOMEDS_Exists(aFile)) continue;
148
149 #ifdef WIN32
150     DeleteFile(aFile.c_str());
151 #else 
152     unlink(aFile.c_str());
153 #endif
154   }
155
156   if(IsDirDeleted) {
157     if(SALOMEDS_Exists(aDirName)) {
158 #ifdef WIN32
159       RemoveDirectory(aDirName.c_str());
160 #else
161       rmdir(aDirName.c_str());
162 #endif
163     }
164   }
165
166 }
167
168 //============================================================================
169 // function : GetNameFromPath
170 // purpose  : Returns the name by the path
171 //============================================================================
172 std::string SALOMEDSImpl_Tool::GetNameFromPath(const std::string& thePath) {
173   if (thePath.empty()) return "";
174   int pos = thePath.rfind('/');
175   if(pos >= 0) return thePath.substr(pos+1, thePath.size());
176   pos = thePath.rfind('\\'); 
177   if(pos >= 0) return thePath.substr(pos+1, thePath.size()); 
178   pos = thePath.rfind('|');
179   if(pos >= 0) return thePath.substr(pos+1, thePath.size()); 
180   return thePath;
181 }
182
183 //============================================================================
184 // function : GetDirFromPath
185 // purpose  : Returns the dir by the path
186 //============================================================================
187 std::string SALOMEDSImpl_Tool::GetDirFromPath(const std::string& thePath) {
188 #ifdef WIN32
189   std::string separator = "\\";
190 #else
191   std::string separator = "/";
192 #endif
193
194   std::string path;
195   if (!thePath.empty()) {
196     int pos = thePath.rfind('/');
197     if (pos < 0) pos = thePath.rfind('\\');
198     if (pos < 0) pos = thePath.rfind('|');
199     
200     if (pos >= 0)
201       path = thePath.substr(0, pos+1);
202     else
203       path = std::string(".") + separator;
204
205 #ifdef WIN32  //Check if the only disk letter is given as path
206     if (path.size() == 2 && path[1] == ':') path += separator;
207 #endif
208     
209     while ( (pos=path.find('|')) >= 0 )
210       path.replace(pos, 1, separator);
211   }
212   
213   return path;
214 }
215
216 //============================================================================
217 // function : 
218 // purpose  : The functions returns a list of substring of initial string 
219 //            divided by given separator
220 //============================================================================
221 std::vector<std::string> SALOMEDSImpl_Tool::splitString(const std::string& theValue, char separator)
222 {
223   std::vector<std::string> vs;
224   if(theValue[0] == separator && theValue.size() == 1) return vs;
225   int pos = theValue.find(separator);
226   if(pos < 0) {
227     vs.push_back(theValue);
228     return vs;
229   }
230  
231   std::string s = theValue;
232   if(s[0] == separator) s = s.substr(1, s.size());
233   while((pos = s.find(separator)) >= 0) {
234     vs.push_back(s.substr(0, pos));
235     s = s.substr(pos+1, s.size());
236   }
237                
238   if(!s.empty() && s[0] != separator) vs.push_back(s);
239   return vs;
240 }
241
242 //============================================================================
243 // function : 
244 // purpose  : The functions returns a list of substring of initial string 
245 //            divided by given separator include empty strings
246 //============================================================================
247
248 std::vector<std::string> treatRepetation(const std::string& theValue);
249
250 std::vector<std::string> treatRepetation(const std::string& theValue)
251 {
252   std::vector<std::string> aResult;
253   int pos = theValue.find(";*=");
254   if(pos < 0 )
255     {
256       aResult.push_back(theValue);
257       return aResult;
258     }
259   std::string val(theValue.substr(0, pos));
260   std::string suffix(theValue.substr(pos+3));
261   int nb;
262   std::istringstream tmp(suffix);
263   tmp >> nb;
264   for(int i=0; i<nb; i++)
265     aResult.push_back(val);
266   return aResult;
267 }
268
269 std::vector<std::string> SALOMEDSImpl_Tool::splitStringWithEmpty(const std::string& theValue, char sep)
270 {
271   std::vector<std::string> aResult;
272   if(theValue[0] == sep ) aResult.push_back(std::string());
273   int pos = theValue.find(sep);
274   if(pos < 0 ) {
275     if(sep == '|')
276       {
277         std::vector<std::string> tmp = treatRepetation(theValue);
278         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
279       }
280     else
281       aResult.push_back(theValue);
282     return aResult;
283   }
284
285   std::string s = theValue;
286   if(s[0] == sep) s = s.substr(1, s.size());
287   while((pos = s.find(sep)) >= 0) {
288     if(sep == '|')
289       {
290         std::vector<std::string> tmp = treatRepetation(s.substr(0, pos));
291         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
292       }
293     else
294       aResult.push_back(s.substr(0, pos));
295     s = s.substr(pos+1, s.size());
296   }
297
298   if(!s.empty() && s[0] != sep) {
299     if(sep == '|')
300       {
301         std::vector<std::string> tmp = treatRepetation(s);
302         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
303       }
304     else
305       aResult.push_back(s);
306   }
307   if(theValue[theValue.size()-1] == sep) aResult.push_back(std::string());
308
309   return aResult;
310 }
311
312 //============================================================================
313 // function : 
314 // purpose  : The functions returns a list of lists of substrings of initial string 
315 //            divided by two given separators include empty strings
316 //============================================================================
317 std::vector< std::vector<std::string> > SALOMEDSImpl_Tool::splitStringWithEmpty(const std::string& theValue, char sep1, char sep2)
318 {
319   std::vector< std::vector<std::string> > aResult;
320   if(theValue.size() > 0) {
321     std::vector<std::string> aSections = splitStringWithEmpty( theValue, sep1 );
322     for( int i = 0, n = aSections.size(); i < n; i++ )
323       aResult.push_back( splitStringWithEmpty( aSections[i], sep2 ) );
324   }
325   return aResult;
326 }
327
328
329 void SALOMEDSImpl_Tool::GetSystemDate(int& year, int& month, int& day, int& hours, int& minutes, int& seconds)
330 {
331 #ifdef WIN32
332   SYSTEMTIME    st;
333
334   GetLocalTime ( &st );
335
336   month = st.wMonth;
337   day = st.wDay;
338   year = st.wYear;
339   hours = st.wHour;
340   minutes = st.wMinute;
341   seconds = st.wSecond;
342 #else
343   struct tm transfert;
344   struct timeval tval;
345   struct timezone tzone;
346   //int status;
347
348   /*status = */ gettimeofday( &tval, &tzone );
349   memcpy(&transfert, localtime((time_t *)&tval.tv_sec), sizeof(tm));
350
351   month    = transfert.tm_mon + 1;
352   day      = transfert.tm_mday;
353   year     = transfert.tm_year + 1900;
354   hours    = transfert.tm_hour;
355   minutes  = transfert.tm_min ;
356   seconds  = transfert.tm_sec ;
357 #endif
358 }
359
360 //Warning undef of Ascii Winwows define
361 #ifdef WIN32
362 # undef GetUserName
363 #endif
364 std::string SALOMEDSImpl_Tool::GetUserName()
365 {
366 #ifdef WIN32
367   char*  pBuff = new char[UNLEN + 1];
368   DWORD  dwSize = UNLEN + 1;
369   std::string retVal;
370   ::GetUserNameA( pBuff, &dwSize );
371   std::string theTmpUserName(pBuff,(int)dwSize -1 );
372   retVal = theTmpUserName;
373   delete [] pBuff;
374   return retVal;
375 #else
376  struct passwd *infos;
377  infos = getpwuid(getuid()); 
378  return std::string(infos->pw_name);
379 #endif
380 }
381