Salome HOME
merge from branch BR_V5_DEV
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_Tool.cxx
1 //  Copyright (C) 2007-2008  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.
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 //  File      : SALOMEDSImpl_Tool.cxx
23 //  Created   : Mon Oct 21 16:24:34 2002
24 //  Author    : Sergey RUIN
25 //  Project   : SALOME
26 //  Module    : SALOMEDSImpl
27 //
28 #include <stdio.h>
29 #include <iostream> 
30 #include <fstream>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "SALOMEDSImpl_Tool.hxx"
35
36 #ifndef WIN32
37 #include <sys/time.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <pwd.h> 
41 #include <unistd.h>
42 #else
43 #include <time.h>
44 #include <lmcons.h>
45 //#include <winbase.h>
46 #include <windows.h>
47 #endif
48
49 using namespace std;
50
51
52
53 bool Exists(const 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 string SALOMEDSImpl_Tool::GetTmpDir()
76 {
77   //Find a temporary directory to store a file
78
79   string aTmpDir;
80
81   char *Tmp_dir = getenv("SALOME_TMP_DIR");
82   if(Tmp_dir != NULL) {
83     aTmpDir = 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 = string("C:\\");
93 #else
94     aTmpDir = 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   string aSubDir(buffer);
103   if(aSubDir.size() <= 1) aSubDir = string("123409876");
104
105   aTmpDir += aSubDir; //Get RND sub directory
106
107   string aDir = aTmpDir;
108   
109   if(Exists(aDir)) {
110     for(aRND = 0; 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 string& theDirectory, 
137                                              const vector<string>& theFiles,
138                                              const bool IsDirDeleted)
139 {
140   string aDirName = theDirectory;
141
142   int i, aLength = theFiles.size();
143   for(i=1; i<=aLength; i++) {
144     string aFile(aDirName);
145     aFile += theFiles[i-1];
146     if(!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(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 string SALOMEDSImpl_Tool::GetNameFromPath(const 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 string SALOMEDSImpl_Tool::GetDirFromPath(const string& thePath) {
187   if (thePath.empty()) return "";
188
189   int pos = thePath.rfind('/');
190   string path;
191   if(pos > 0) {
192     path = thePath.substr(0, pos+1);
193   }
194   if(path.empty()) {
195     pos = thePath.rfind('\\');
196     if(pos > 0) path = thePath.substr(0, pos+1); 
197   }
198   if(path.empty()) {
199     pos = thePath.rfind('|');
200     if(pos > 0) path = thePath.substr(0, pos+1); 
201   }
202   if(path.empty()) {
203     path = thePath+"/";
204   }
205   
206 #ifdef WIN32  //Check if the only disk letter is given as path
207   if(path.size() == 2 && path[1] == ':') path +='\\';
208 #endif
209
210   for(int i = 0, len = path.size(); i<len; i++) 
211     if(path[i] == '|') path[i] = '/';
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 vector<string> SALOMEDSImpl_Tool::splitString(const string& theValue, char separator)
221 {
222   vector<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   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 vector<string> SALOMEDSImpl_Tool::splitStringWithEmpty(const string& theValue, char sep)
247 {
248   vector<string> aResult;
249   if(theValue[0] == sep ) aResult.push_back(string());
250   int pos = theValue.find(sep);
251   if(pos < 0 ) {
252     aResult.push_back(theValue);
253     return aResult;
254   }
255
256   string s = theValue;
257   if(s[0] == sep) s = s.substr(1, s.size());
258   while((pos = s.find(sep)) >= 0) {
259     aResult.push_back(s.substr(0, pos));
260     s = s.substr(pos+1, s.size());
261   }
262
263   if(!s.empty() && s[0] != sep) aResult.push_back(s);
264   if(theValue[theValue.size()-1] == sep) aResult.push_back(string());
265
266   return aResult;
267 }
268
269 //============================================================================
270 // function : 
271 // purpose  : The functions returns a list of lists of substrings of initial string 
272 //            divided by two given separators include empty strings
273 //============================================================================
274 vector< vector<string> > SALOMEDSImpl_Tool::splitStringWithEmpty(const string& theValue, char sep1, char sep2)
275 {
276   vector< vector<string> > aResult;
277   if(theValue.size() > 0) {
278     vector<string> aSections = splitStringWithEmpty( theValue, sep1 );
279     for( int i = 0, n = aSections.size(); i < n; i++ )
280       aResult.push_back( splitStringWithEmpty( aSections[i], sep2 ) );
281   }
282   return aResult;
283 }
284
285
286 void SALOMEDSImpl_Tool::GetSystemDate(int& year, int& month, int& day, int& hours, int& minutes, int& seconds)
287 {
288 #ifdef WIN32
289   SYSTEMTIME    st;
290
291   GetLocalTime ( &st );
292
293   month = st.wMonth;
294   day = st.wDay;
295   year = st.wYear;
296   hours = st.wHour;
297   minutes = st.wMinute;
298   seconds = st.wSecond;
299 #else
300   struct tm transfert;
301   struct timeval tval;
302   struct timezone tzone;
303   int status;
304
305  status = gettimeofday( &tval, &tzone );
306  memcpy(&transfert, localtime((time_t *)&tval.tv_sec), sizeof(tm));
307
308  month    = transfert.tm_mon + 1;
309  day      = transfert.tm_mday;
310  year     = transfert.tm_year + 1900;
311  hours    = transfert.tm_hour;
312  minutes  = transfert.tm_min ;
313  seconds  = transfert.tm_sec ;
314 #endif
315 }
316
317 //Warning undef of Ascii Winwows define
318 #ifdef WIN32
319 # undef GetUserName
320 #endif
321 string SALOMEDSImpl_Tool::GetUserName()
322 {
323 #ifdef WIN32
324   char*  pBuff = new char[UNLEN + 1];
325   DWORD  dwSize = UNLEN + 1;
326   string retVal;
327   ::GetUserNameA( pBuff, &dwSize );
328   string theTmpUserName(pBuff,(int)dwSize -1 );
329   retVal = theTmpUserName;
330   delete [] pBuff;
331   return retVal;
332 #else
333  struct passwd *infos;
334  infos = getpwuid(getuid()); 
335  return string(infos->pw_name);
336 #endif
337 }
338
339
340
341
342
343