Salome HOME
Merge branch 'omu/SalomeLauncher'
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_Tool.cxx
1 // Copyright (C) 2007-2015  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) {
83     aTmpDir = std::string(Tmp_dir);
84 #ifdef WIN32
85     if(aTmpDir[aTmpDir.size()-1] != '\\') aTmpDir+='\\';
86 #else
87     if(aTmpDir[aTmpDir.size()-1] != '/') aTmpDir+='/';
88 #endif      
89   }
90   else {
91 #ifdef WIN32
92     aTmpDir = std::string("C:\\");
93 #else
94     aTmpDir = std::string("/tmp/");
95 #endif
96   }
97
98   srand((unsigned int)time(NULL));
99   int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
100   char buffer[127];
101   sprintf(buffer, "%d", aRND);
102   std::string aSubDir(buffer);
103   if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
104
105   aTmpDir += aSubDir; //Get RND sub directory
106
107   std::string aDir = aTmpDir;
108   
109   if(SALOMEDS_Exists(aDir)) {
110     for(aRND = 0; SALOMEDS_Exists(aDir); aRND++) {
111       sprintf(buffer, "%d", aRND);
112       aDir = aTmpDir+buffer;  //Build a unique directory name
113     }
114   }
115
116 #ifdef WIN32
117   if(aDir[aTmpDir.size()-1] != '\\') aDir+='\\';
118 #else
119   if(aDir[aTmpDir.size()-1] != '/') aDir+='/';
120 #endif
121
122
123 #ifdef WIN32
124   CreateDirectory(aDir.c_str(), NULL);
125 #else
126   mkdir(aDir.c_str(), 0x1ff); 
127 #endif
128
129   return aDir;
130 }
131
132 //============================================================================
133 // function : RemoveTemporaryFiles
134 // purpose  : Removes files listed in theFileList
135 //============================================================================
136 void SALOMEDSImpl_Tool::RemoveTemporaryFiles(const std::string& theDirectory, 
137                                              const std::vector<std::string>& theFiles,
138                                              const bool IsDirDeleted)
139 {
140   std::string aDirName = theDirectory;
141
142   int i, aLength = theFiles.size();
143   for(i=1; i<=aLength; i++) {
144     std::string aFile(aDirName);
145     aFile += theFiles[i-1];
146     if(!SALOMEDS_Exists(aFile)) continue;
147
148 #ifdef WIN32
149     DeleteFile(aFile.c_str());
150 #else 
151     unlink(aFile.c_str());
152 #endif
153   }
154
155   if(IsDirDeleted) {
156     if(SALOMEDS_Exists(aDirName)) {
157 #ifdef WIN32
158       RemoveDirectory(aDirName.c_str());
159 #else
160       rmdir(aDirName.c_str());
161 #endif
162     }
163   }
164
165 }
166
167 //============================================================================
168 // function : GetNameFromPath
169 // purpose  : Returns the name by the path
170 //============================================================================
171 std::string SALOMEDSImpl_Tool::GetNameFromPath(const std::string& thePath) {
172   if (thePath.empty()) return "";
173   int pos = thePath.rfind('/');
174   if(pos >= 0) return thePath.substr(pos+1, thePath.size());
175   pos = thePath.rfind('\\'); 
176   if(pos >= 0) return thePath.substr(pos+1, thePath.size()); 
177   pos = thePath.rfind('|');
178   if(pos >= 0) return thePath.substr(pos+1, thePath.size()); 
179   return thePath;
180 }
181
182 //============================================================================
183 // function : GetDirFromPath
184 // purpose  : Returns the dir by the path
185 //============================================================================
186 std::string SALOMEDSImpl_Tool::GetDirFromPath(const std::string& thePath) {
187 #ifdef WIN32
188   std::string separator = "\\";
189 #else
190   std::string separator = "/";
191 #endif
192
193   std::string path;
194   if (!thePath.empty()) {
195     int pos = thePath.rfind('/');
196     if (pos < 0) pos = thePath.rfind('\\');
197     if (pos < 0) pos = thePath.rfind('|');
198     
199     if (pos >= 0)
200       path = thePath.substr(0, pos+1);
201     else
202       path = std::string(".") + separator;
203
204 #ifdef WIN32  //Check if the only disk letter is given as path
205     if (path.size() == 2 && path[1] == ':') path += separator;
206 #endif
207     
208     while ( (pos=path.find('|')) >= 0 )
209       path.replace(pos, 1, separator);
210   }
211   
212   return path;
213 }
214
215 //============================================================================
216 // function : 
217 // purpose  : The functions returns a list of substring of initial string 
218 //            divided by given separator
219 //============================================================================
220 std::vector<std::string> SALOMEDSImpl_Tool::splitString(const std::string& theValue, char separator)
221 {
222   std::vector<std::string> vs;
223   if(theValue[0] == separator && theValue.size() == 1) return vs;
224   int pos = theValue.find(separator);
225   if(pos < 0) {
226     vs.push_back(theValue);
227     return vs;
228   }
229  
230   std::string s = theValue;
231   if(s[0] == separator) s = s.substr(1, s.size());
232   while((pos = s.find(separator)) >= 0) {
233     vs.push_back(s.substr(0, pos));
234     s = s.substr(pos+1, s.size());
235   }
236                
237   if(!s.empty() && s[0] != separator) vs.push_back(s);
238   return vs;
239 }
240
241 //============================================================================
242 // function : 
243 // purpose  : The functions returns a list of substring of initial string 
244 //            divided by given separator include empty strings
245 //============================================================================
246
247 std::vector<std::string> treatRepetation(const std::string& theValue);
248
249 std::vector<std::string> treatRepetation(const std::string& theValue)
250 {
251   std::vector<std::string> aResult;
252   int pos = theValue.find(";*=");
253   if(pos < 0 )
254     {
255       aResult.push_back(theValue);
256       return aResult;
257     }
258   std::string val(theValue.substr(0, pos));
259   std::string suffix(theValue.substr(pos+3));
260   int nb;
261   std::istringstream tmp(suffix);
262   tmp >> nb;
263   for(int i=0; i<nb; i++)
264     aResult.push_back(val);
265   return aResult;
266 }
267
268 std::vector<std::string> SALOMEDSImpl_Tool::splitStringWithEmpty(const std::string& theValue, char sep)
269 {
270   std::vector<std::string> aResult;
271   if(theValue[0] == sep ) aResult.push_back(std::string());
272   int pos = theValue.find(sep);
273   if(pos < 0 ) {
274     if(sep == '|')
275       {
276         std::vector<std::string> tmp = treatRepetation(theValue);
277         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
278       }
279     else
280       aResult.push_back(theValue);
281     return aResult;
282   }
283
284   std::string s = theValue;
285   if(s[0] == sep) s = s.substr(1, s.size());
286   while((pos = s.find(sep)) >= 0) {
287     if(sep == '|')
288       {
289         std::vector<std::string> tmp = treatRepetation(s.substr(0, pos));
290         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
291       }
292     else
293       aResult.push_back(s.substr(0, pos));
294     s = s.substr(pos+1, s.size());
295   }
296
297   if(!s.empty() && s[0] != sep) {
298     if(sep == '|')
299       {
300         std::vector<std::string> tmp = treatRepetation(s);
301         std::copy(tmp.begin(), tmp.end(), std::back_insert_iterator< std::vector<std::string> >(aResult));
302       }
303     else
304       aResult.push_back(s);
305   }
306   if(theValue[theValue.size()-1] == sep) aResult.push_back(std::string());
307
308   return aResult;
309 }
310
311 //============================================================================
312 // function : 
313 // purpose  : The functions returns a list of lists of substrings of initial string 
314 //            divided by two given separators include empty strings
315 //============================================================================
316 std::vector< std::vector<std::string> > SALOMEDSImpl_Tool::splitStringWithEmpty(const std::string& theValue, char sep1, char sep2)
317 {
318   std::vector< std::vector<std::string> > aResult;
319   if(theValue.size() > 0) {
320     std::vector<std::string> aSections = splitStringWithEmpty( theValue, sep1 );
321     for( int i = 0, n = aSections.size(); i < n; i++ )
322       aResult.push_back( splitStringWithEmpty( aSections[i], sep2 ) );
323   }
324   return aResult;
325 }
326
327
328 void SALOMEDSImpl_Tool::GetSystemDate(int& year, int& month, int& day, int& hours, int& minutes, int& seconds)
329 {
330 #ifdef WIN32
331   SYSTEMTIME    st;
332
333   GetLocalTime ( &st );
334
335   month = st.wMonth;
336   day = st.wDay;
337   year = st.wYear;
338   hours = st.wHour;
339   minutes = st.wMinute;
340   seconds = st.wSecond;
341 #else
342   struct tm transfert;
343   struct timeval tval;
344   struct timezone tzone;
345   int status;
346
347  status = gettimeofday( &tval, &tzone );
348  memcpy(&transfert, localtime((time_t *)&tval.tv_sec), sizeof(tm));
349
350  month    = transfert.tm_mon + 1;
351  day      = transfert.tm_mday;
352  year     = transfert.tm_year + 1900;
353  hours    = transfert.tm_hour;
354  minutes  = transfert.tm_min ;
355  seconds  = transfert.tm_sec ;
356 #endif
357 }
358
359 //Warning undef of Ascii Winwows define
360 #ifdef WIN32
361 # undef GetUserName
362 #endif
363 std::string SALOMEDSImpl_Tool::GetUserName()
364 {
365 #ifdef WIN32
366   char*  pBuff = new char[UNLEN + 1];
367   DWORD  dwSize = UNLEN + 1;
368   std::string retVal;
369   ::GetUserNameA( pBuff, &dwSize );
370   std::string theTmpUserName(pBuff,(int)dwSize -1 );
371   retVal = theTmpUserName;
372   delete [] pBuff;
373   return retVal;
374 #else
375  struct passwd *infos;
376  infos = getpwuid(getuid()); 
377  return std::string(infos->pw_name);
378 #endif
379 }
380
381
382
383
384
385