Toolbox.cpp 7.83 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#include "Toolbox.h"

#include <ctime>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cstring>

#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>

#include "magic.h"

namespace TREPS
{
	namespace Common
	{
		//list of available char for string generation
		static const char alphanum[] =
				"0123456789"
				"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
				"abcdefghijklmnopqrstuvwxyz";
	
		string genRandomStr(int len)
		{
			string s = "";
			for (int i = 0; i < len; ++i)
				s += alphanum[rand() % (sizeof(alphanum) - 1)];
			return s;
		}

		long int getCrtTime(void)
		{
			//time in UTC
			return static_cast<long int>(time(NULL));
		}
		
		string getCrtTimeStr(void)
		{
			time_t t = time(NULL);
			stringstream strm;
			strm << t;
			return strm.str();
		}

		
		void tmToTime(struct tm tm, t_Time &t)
		{
			t.ho = tm.tm_hour;
			t.mi = tm.tm_min;
			t.se = tm.tm_sec;
			t.ye = tm.tm_year + 1900;
			t.mo = tm.tm_mon+1;
			t.da = tm.tm_mday;
			t.ml = 0;
		}

		void setDOY(t_Time &t, long int doy)
		{
			struct tm tm;
			memset(&tm,0,sizeof(struct tm));

			tm.tm_year = t.ye-1900;
			tm.tm_mday = doy;

			mktime(&tm);

			t.mo = tm.tm_mon+1;
			t.da = tm.tm_mday;
		}

		long int getDOY(t_Time t)
		{
			struct tm tm;
			memset(&tm,0,sizeof(struct tm));

			tm.tm_year  = t.ye-1900;
			tm.tm_mon = t.mo-1;
			tm.tm_mday = t.da;

			mktime(&tm);

			return tm.tm_yday+1;
		}

		bool isLeapYear(long int year)
		{
			return ((year & 3) == 0)&&(((year % 100) != 0)||((year % 400)==0));
		}
		
		string getFileNameStr(const char *file_path)
		{
			string str = file_path;
			return str.substr( str.find_last_of("/\\") + 1 );
		}
		
		string getTRIMStr(const char *s)
		{
			string str = s;
			str.erase (str.find_last_not_of (" \n\r\t") + 1);
			str.erase (0, str.find_first_not_of (" \n\r\t"));
			return str;
		}

		string intToStr(const int n)
		{
			stringstream ss;
			ss << n;
                        return ss.str();
		}

		string longToStr(const long int n)
		{
			stringstream ss;
			ss << n;
			return ss.str();
		}

		string longlongToStr(const long long int n)
                {
			stringstream ss;
			ss << n;
			return ss.str();
		}

		string doubleToStr(const double d)
		{
			char tmp[1024];
			memset(tmp,0,sizeof(char)*1024);
			sprintf(tmp,"%.10f",d);
			string s = tmp;
			return s;
		}

		string replaceInStr(const char *s, const char *f, const char *t)
		{
			//replace f by t in s
			string str = s;

			size_t pos;
			pos = str.find(f);

			while (pos != string::npos)
			{
				str.replace(pos, strlen(f), t);
				pos = str.find(f);
			}

			return str;
		}

		string getFileMIMEType(const char *file_path)
		{
			magic_t myt = magic_open(MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME);
			if(magic_errno(myt) > 0)
				return "";
			magic_load(myt,NULL);
			if(magic_errno(myt) > 0)
                                return "";
			const char *r =  magic_file(myt,file_path);
			string res = "";
			if (r != NULL)
				res = r;
			magic_close(myt);
			return res;
		}
		
		string getPathCorrection(const char *file_path)
		{
			string str = file_path;
			if (str.length() > 0)
				if (str[str.length()-1] != '/')
					str += "/";
			return str;
		}
	
		string getExecPath(void)
		{
			//get the application path
			string fullFileName = "";

			string path = "";

			//get application pid
			pid_t pid = getpid();
			char buf[20] = {0};
			sprintf(buf,"%d",pid);

			//
			string _link = "/proc/";
			_link.append(buf);
			_link.append( "/exe");

			char proc[512];
			int ch = readlink(_link.c_str(),proc,512);
			if (ch != -1)
			{
				proc[ch] = 0;
				path = proc;
				string::size_type t = path.find_last_of("/");
				path = path.substr(0,t);
			}

			fullFileName = path + string("/");

			return fullFileName;
		}
	
		bool isDir(const char *dir_path)
		{
			struct stat s_buf;

    			if (stat(dir_path, &s_buf))
        			return false;

			return (S_ISDIR(s_buf.st_mode) > 0);
		}

		bool haveDirWritePermission(const char *dir_path)
		{
			//test write permission for a directory
			if (!isDir(dir_path))
				return false;

			struct stat s_buf;

			if (stat(dir_path, &s_buf))
				return false;

			return (s_buf.st_mode & S_IWUSR);	
		}

		bool createDir(const char *dir_path, mode_t mode)
		{
			mode_t process_mask = umask(0);
			bool res = (mkdir(dir_path, mode) != -1);
			umask(process_mask);
			return res;
		}

		bool deleteDir(const char *dir_path)
		{
			//delete dir recursively
			DIR*            dp;
    			struct dirent*  ep;
    			string crtPath;

			if (!isDir(dir_path))
				return false;

    			dp = opendir(dir_path);

    			while ((ep = readdir(dp)) != NULL)
			{
        			crtPath = dir_path;
				crtPath = getPathCorrection(crtPath.c_str());
				crtPath += ep->d_name;
        			if (isDir(crtPath.c_str()))
				{
					if (crtPath.compare(".") || crtPath.compare(".."))
						continue;
					if (!deleteDir(crtPath.c_str()))
					{
						closedir(dp);
						return false;
					}
				}
        			else if (unlink(crtPath.c_str()) == -1)
				{
					closedir(dp);
					return false;
				}
    			}

    			closedir(dp);
    			return (rmdir(dir_path) != -1);
		}

		bool isFileExist(const char *file_path)
		{
			ifstream f(file_path);
			if (f.good())
			{
				f.close();
				return true;
			}

			f.close();
			return false;
		}

		bool deleteFile(const char *file_path)
		{
			if (!isFileExist(file_path))
				return false;
			return (unlink(file_path) != -1);
		}

		bool haveFileWritePermission(const char *file_path)
		{
			//test file write permission
			if (!isFileExist(file_path))
                                return false;

			struct stat s_buf;

			if (stat(file_path, &s_buf))
				return false;

			return (s_buf.st_mode & S_IWUSR);
                }

		int getFileSize(const char *file_path)
		{
			struct stat s_buf;

			if (stat(file_path, &s_buf))
				return -1;

			return s_buf.st_size;
		}

		#define TREPS_SYSCMDERR_POPEN     -100
		#define TREPS_SYSCMDERR_PCLOSE    -101
		#define TREPS_SYSCMDERR_SIGNALED  -102
		#define TREPS_SYSCMDERR_COREDUMP  -103
		#define TREPS_SYSCMDERR_STOPPED   -104
		#define TREPS_SYSCMDERR_CONTINUED -105
		#define TREPS_SYSCMDERR_UNKNOWN   -106

		int executeSystemCommand(const char *cmd, string &output)
		{
			output = "";

			signal(SIGCHLD, SIG_DFL);

			FILE* pipe = popen(cmd, "r");

			if (!pipe)
				return TREPS_SYSCMDERR_POPEN;

			const int max_buffer = 2048;
			char buffer[max_buffer];

    			while (fgets(buffer, max_buffer, pipe) != NULL)
				output += buffer;

			int status;
			if ((status = pclose(pipe)) == -1)
				return TREPS_SYSCMDERR_PCLOSE;

			if (WIFEXITED(status))
				return WEXITSTATUS(status);

			if (WIFSIGNALED(status))
			{
				if (WCOREDUMP(status))
					return TREPS_SYSCMDERR_COREDUMP;
				return TREPS_SYSCMDERR_SIGNALED;
			}

			if (WIFSTOPPED(status))
				return TREPS_SYSCMDERR_STOPPED;

			if (WIFCONTINUED(status))
				return TREPS_SYSCMDERR_CONTINUED;

			return TREPS_SYSCMDERR_UNKNOWN;
		}

		bool sysCmdError(int status)
		{
			return ((status == TREPS_SYSCMDERR_POPEN) || (status == TREPS_SYSCMDERR_PCLOSE) || (status == TREPS_SYSCMDERR_SIGNALED) ||
				(status == TREPS_SYSCMDERR_COREDUMP) || (status == TREPS_SYSCMDERR_STOPPED) || (status == TREPS_SYSCMDERR_CONTINUED) ||
				(status == TREPS_SYSCMDERR_UNKNOWN));
		}

		int getCrtProcId(void)
		{
			return (int)getpid();
		}

		bool procIsRunning(int procId)
		{
			//test if a process is running
			string procDir = "/proc/";
			procDir += intToStr(procId);
			return isDir(procDir.c_str());
		}

		void doSleep(long int sec)
		{
			sleep(sec);
		}

		string fieldTypeToStr(t_FieldType type)
		{
			switch (type)
			{
				case FT_TIME :
					return "time";
				case FT_FLOAT :
					return "float";
				case FT_DOUBLE :
					return "double";
				case FT_SHORT :
					return "short";
				case FT_INT :
					return "int";
				case FT_LONG :
					return "long";
				case FT_UNKNOWN :
					return "";
			}
			return "";
		}
	}
}